prometheus integration

This commit is contained in:
osmarks 2021-01-27 19:38:21 +00:00
parent 6d18a5c56e
commit 4e1dc6b337
4 changed files with 28 additions and 9 deletions

View File

@ -6,9 +6,12 @@ import discord
from datetime import datetime
import re
import collections
import prometheus_client
import util
achievements_achieved = prometheus_client.Counter("abr_achievements", "Achievements achieved by users")
Achievement = collections.namedtuple("Achievement", ["name", "condition", "description"])
achievements = {
@ -40,6 +43,7 @@ async def achieve(bot: commands.Bot, message: discord.Message, achievement):
e = util.make_embed(description=description, title="Achievement achieved!", color=util.hashbow(achievement))
e.set_thumbnail(url=await util.get_asset(bot, f"achievements/{achievement}.png"))
await channel.send(embed=e)
achievements_achieved.inc()
await bot.database.execute("INSERT INTO achievements VALUES (?, ?, ?)", (uid, achievement, util.timestamp()))
await bot.database.commit()
logging.info("awarded achievement %s to %s", message.author.name, achievement)

View File

@ -2,12 +2,16 @@ import util
import random
import logging
import discord
import prometheus_client
heavserver_members = prometheus_client.Gauge("abr_heavserver_members", "Current member count of heavserver")
def setup(bot):
@bot.listen()
async def on_member_join(member):
if member.guild.id == util.config["heavserver"]["id"]:
logging.info("%s (%d) joined heavserver", member.display_name, member.id)
heavserver_members.set(len(bot.get_guild(util.config["heavserver"]["id"]).members))
if member.bot:
await member.add_roles(discord.utils.get(member.guild.roles, id=util.config["heavserver"]["quarantine_role"]))
await member.add_roles(discord.utils.get(member.guild.roles, id=random.choice(util.config["heavserver"]["moderator_roles"][:])))

View File

@ -12,6 +12,8 @@ import traceback
import random
import rolldice
import collections
import prometheus_client
import prometheus_async.aio
import typing
from numpy.random import default_rng
@ -35,8 +37,11 @@ cleaner = discord.ext.commands.clean_content()
def clean(ctx, text):
return cleaner.convert(ctx, text)
messages = prometheus_client.Counter("abr_messages", "Messages seen/handled by bot")
command_invocations = prometheus_client.Counter("abr_command_invocations", "Total commands invoked (includes failed)")
@bot.event
async def on_message(message):
messages.inc()
words = message.content.split(" ")
if len(words) == 10 and message.author.id == 435756251205468160:
await message.channel.send(util.unlyric(message.content))
@ -44,14 +49,17 @@ async def on_message(message):
if message.author == bot.user or message.author.discriminator == "0000": return
ctx = await bot.get_context(message)
if not ctx.valid: return
command_invocations.inc()
await bot.invoke(ctx)
command_errors = prometheus_client.Counter("abr_errors", "Count of errors encountered in executing commands.")
@bot.event
async def on_command_error(ctx, err):
#print(ctx, err)
if isinstance(err, (commands.CommandNotFound, commands.CheckFailure)): return
if isinstance(err, commands.MissingRequiredArgument): return await ctx.send(embed=util.error_embed(str(err)))
try:
command_errors.inc()
trace = re.sub("\n\n+", "\n", "\n".join(traceback.format_exception(err, err, err.__traceback__)))
logging.error("command error occured (in %s)", ctx.invoked_with, exc_info=err)
await ctx.send(embed=util.error_embed(util.gen_codeblock(trace), title="Internal error"))
@ -168,18 +176,15 @@ async def random_int(ctx, *, dice):
await ctx.send("Disabled until CPU use restrictions can be done.")
#await ctx.send(rolldice.roll_dice(dice)[0])
bad_things = ["lyric", "solarflame", "lyric", "319753218592866315", "andrew", "6", "c++", "", "communism"]
good_things = ["potato", "heav", "gollark", "helloboi", "bee", "hellboy", "rust", "ferris", "crab", "transistor", "endos", "make esolang"]
negations = ["not", "bad", "un", "kill", "n't", "¬", "counter"]
def weight(thing):
lthing = thing.lower()
weight = 1.0
if lthing == "c": weight *= 0.3
for bad_thing in bad_things:
for bad_thing in util.config["autobias"]["bad_things"]:
if bad_thing in lthing: weight *= 0.5
for good_thing in good_things:
for good_thing in util.config["autobias"]["good_things"]:
if good_thing in lthing: weight *= 2.0
for negation in negations:
for negation in util.config["autobias"]["negations"]:
for _ in range(lthing.count(negation)): weight = 1 / weight
return weight
@ -229,6 +234,7 @@ async def run_bot():
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.create_task(prometheus_async.aio.web.start_http_server(port=config["metrics_port"]))
try:
loop.run_until_complete(run_bot())
except KeyboardInterrupt:

View File

@ -2,9 +2,12 @@ import json
import logging
from datetime import datetime, timezone
import discord.ext.tasks as tasks
import prometheus_client
import util
reminders_fired = prometheus_client.Counter("abr_reminders", "Reminders successfully delivered to users")
def setup(bot):
@bot.command(brief="Set a reminder to be reminded about later.", rest_is_raw=True, help="""Sets a reminder which you will (probably) be reminded about at/after the specified time.
All times are UTC.
@ -86,14 +89,16 @@ def setup(bot):
print("trying", method_name, rid)
try:
await func(extra, text)
to_expire.append(rid)
reminders_fired.inc()
to_expire.append((1, rid)) # 1 = expired normally
break
except Exception as e: logging.warning("failed to send %d to %s", rid, method_name, exc_info=e)
except Exception as e:
logging.warning("Could not send reminder %d", rid, exc_info=e)
for expiry_id in to_expire:
to_expire.append((2, rid)) # 2 = errored
for expiry_type, expiry_id in to_expire:
logging.info("Expiring reminder %d", expiry_id)
await bot.database.execute("UPDATE reminders SET expired = 1 WHERE id = ?", (expiry_id,))
await bot.database.execute("UPDATE reminders SET expired = ? WHERE id = ?", (expiry_type, expiry_id))
await bot.database.commit()
@remind_worker.before_loop