Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
)
return await ctx.channel.send(
msgs['errors']['not_started']
)
if ctx.guild:
logging.info(f"{ctx.author.id} in {ctx.guild.id}: {ctx.clean_content}")
else:
logging.info(f"{ctx.author.id} in DM: {ctx.clean_content}")
help_cmd = tuple(map(lambda t: t + "help", bot.command_prefix))
if ctx.content.lower() in help_cmd:
# send help command
msgs = await lang.get_lang(
lang.FakeCtxObject(bot, ctx.author)
)
if not settings.UseBetaBot:
datadog.statsd.increment(
'bot.commands_run',
tags=["command:help"]
)
return await ctx.channel.send(
embed=lang.EmbedBuilder(msgs['help_command'])
)
else:
splitter = ctx.content.split(' && ')
for s in splitter:
ctx.content = s
await bot.process_commands(ctx)
elif ctx.guild is None:
return
except Exception:
await ctx.channel.send(
f"An unexpected error occurred:\n{traceback.format_exc()}"
if language in _.translations.keys():
await self.bot.mongo.config.guilds.find_one_and_update(
{'guild_id': str(g.id)}, {'$set': {'language': language}}, upsert=True
)
else:
language = 'en'
em = discord.Embed(
title=f'Added to {g.name} ({g.id})',
description=f'{len(g.members)} members\nLanguage: {language}\n{info}',
timestamp=datetime.datetime.utcnow(),
color=0x0cc243
)
await self.bot.guild_hook.send(embed=em)
datadog.statsd.increment('statsy.joined', 1)
if isinstance(ctx.channel, discord.TextChannel):
ctx.language = (await self.bot.mongo.config.guilds.find_one({'guild_id': str(ctx.guild.id)}) or {}).get('language', 'messages')
else:
ctx.language = 'messages'
guild_id = getattr(ctx.guild, 'id', 'DM')
try:
datadog.statsd.increment('statsy.magic_caching.check', 1, [f'user:{user.id}', f'guild:{guild_id}', 'game:clashroyale'])
tag = await self.resolve_tag(ctx, None)
try:
player = await self.request(ctx, 'get_player', tag, reason='magic caching')
except ValueError:
return
datadog.statsd.increment('statsy.magic_caching.request', 1, [f'user:{user.id}', f'guild:{guild_id}', 'game:clashroyale'])
await self.request(ctx, 'get_player_chests', tag)
try:
await self.request(ctx, 'get_clan', player.clan.tag, reason='magic caching')
await self.request(ctx, 'get_clan_war', player.clan.tag, reason='magic caching')
except AttributeError:
pass
except (utils.NoTag, clashroyale.RequestError):
pass
def submit_metrics(self):
'''
Submit metrics to datadog
'''
self.log.info('Submitting metrics')
took = int(time.time()) - self.start_time
input_id = self.inputs['bam'].node_id
tags = [
'alignment_type:{}'.format(self.name),
'alignment_host:{}'.format(socket.gethostname()),
]
statsd.event(
'{} aligned'.format(input_id),
'successfully aligned {} in {} minutes'.format(input_id, took / 60),
source_type_name='harmonization',
alert_type='success',
tags=tags
)
with self.graph.session_scope():
total = self.bam_files.count()
done = self.bam_files.filter(File.derived_files.any()).count()
self.log.info('%s bams aligned out of %s', done, total)
statsd.gauge('harmonization.completed_bams',
done,
tags=tags)
statsd.gauge('harmonization.total_bams',
def timing(self, key, value, instance=None, tags=None, sample_rate=1):
if tags is None:
tags = {}
if self.tags:
tags.update(self.tags)
if instance:
tags["instance"] = instance
if tags:
tags = [u"{}:{}".format(*i) for i in tags.items()]
statsd.timing(self._get_key(key), value, sample_rate=sample_rate, tags=tags)
def submit_metrics(self):
'''
Submit metrics to datadog
'''
self.log.info('Submitting metrics')
took = int(time.time()) - self.start_time
input_id = self.inputs['fastq_tarball'].node_id
tags = [
'alignment_type:{}'.format(self.name),
'alignment_host:{}'.format(socket.gethostname()),
]
statsd.event(
'{} aligned'.format(input_id),
'successfully aligned {} in {} minutes'.format(input_id, took / 60),
source_type_name='harmonization',
alert_type='success',
tags=tags
)
with self.graph.session_scope():
total = self.fastq_files.count()
done = self.fastq_files.filter(File.derived_files.any()).count()
self.log.info('%s bams aligned out of %s', done, total)
statsd.gauge('harmonization.completed_fastqs',
done,
tags=tags)
statsd.gauge('harmonization.total_fastqs',
len(ann_docs),
len(project_docs))
self.log.info("Validating docs produced")
self.converter.validate_docs(case_docs, file_docs, ann_docs, project_docs)
self.log.info("Deploying new ES index with new docs and bumping alias")
new_index = self.deploy(case_docs, file_docs, ann_docs, project_docs,
roll_alias=roll_alias)
with self.graph.session_scope() as session:
for expired_node in to_delete:
node = self.graph.nodes(expired_node.__class__)\
.ids(expired_node.node_id)\
.scalar()
if node:
self.log.info("Deleting %s", node)
session.delete(node)
statsd.event(
"esbuild finished",
"successfully built index {}".format(new_index),
source_type_name="esbuild",
alert_type="success",
tags=["es_index:{}".format(new_index)],
)
def on_gateway_event(self, event):
metadata = {
'event': event.__class__.__name__,
}
if hasattr(event, 'guild_id'):
metadata['guild_id'] = event.guild_id
elif hasattr(event, 'guild') and event.guild:
metadata['guild_id'] = event.guild.id
statsd.increment('gateway.events.received', tags=to_tags(metadata))
# NOTE(sileht): check state change so we have to run "run" or "cancel"
report = exec_action(
method_name,
rule,
action,
installation_id,
installation_token,
event_type,
data,
pull,
missing_conditions,
)
message = "`%s` executed" % method_name
if report and report[0] is not None and method_name == "run":
statsd.increment("engine.actions.count", tags=["name:%s" % action])
if report:
conclusion, title, summary = report
status = "completed" if conclusion else "in_progress"
try:
check_api.set_check_run(
pull.g_pull,
check_name,
status,
conclusion,
output={"title": title, "summary": summary},
)
except Exception:
pull.log.error("Fail to post check `%s`", check_name, exc_info=True)
conclusions[check_name] = conclusion
else:
async def post_stats(bot):
await change_presence(bot)
async with aiohttp.ClientSession() as session:
payload = {
"cluster_index": bot.cluster_index,
"guild_count": len(bot.guilds),
"member_count": len(list(bot.get_all_members())),
"active_voice_sessions": len(bot.active_vc),
"latencies": bot.latencies,
"total_shards": bot.shard_count
}
if payload['cluster_index'] == 0:
datadog.statsd.open_buffer()
datadog.statsd.gauge(
'bot.notifications',
r.table('notifications').count().run(bot.rethink, durability="soft")
)
datadog.statsd.gauge(
'bot.live_checks',
r.table('live_role').count().run(bot.rethink, durability="soft")
)
datadog.statsd.close_buffer()
headers = {
"X-Auth-Key": settings.DashboardKey
}
async with session.post("https://api.twitchbot.io/metrics", data=json.dumps(payload), headers=headers) as re:
if not re.status == 200:
t = await re.text()
logging.error(f"Failed to post cluster stats ({re.status}): {t}")