import re import logging import niobot import typing if typing.TYPE_CHECKING: from ..main import NonsenseBot class MemeteraCounter(niobot.Module): ROOM_IDS = { "!gJtz8vGvObJTcs8eYT:puppygock.gay", "!n8DKU1BeeJilOJXDPr:seirdy.one", "!CvZqWrEc2aKtoCoZo4:puppygock.gay" } USER_IDS = { "@june:awawawawawawawawawawawawawawawawawawawawawawawawawawawawawawaw.gay", "@june:constellatory.net", "@june:girlboss.ceo", "@june:itzzen.net", "@strawberry:transfem.dev", "@strawberry:puppygock.gay", "@girlbossceo:matrix.org", "@strawberry:sulian.eu" } WORDS = { "memetera": re.compile(r"^memetera$", re.IGNORECASE), "comma": re.compile(r",") } bot: "NonsenseBot" log = logging.getLogger(__name__) @niobot.event("message") async def on_message(self, room: niobot.MatrixRoom, event: niobot.RoomMessage): if not isinstance(event, niobot.RoomMessageFormatted): return if self.bot.is_old(event): self.log.debug("Ignoring old event") return if room.room_id not in self.ROOM_IDS: self.log.debug("Ignoring non-interesting event in %s", room.room_id) return if event.sender not in self.USER_IDS: self.log.debug("Ignoring uninteresting event by %s in %s", event.sender, room.room_id) return if not self.bot.redis: self.log.warning("Redis is not configured!") return self.log.debug("Interested in event %r in %r by %r", event.event_id, room.room_id, event.sender) counts = {} lower_body = event.body.casefold() for word, regex in self.WORDS.items(): word_count = len(regex.findall(lower_body)) self.log.debug("%d results for %r", word_count, word) if word_count: self.log.debug("June said %r %d times in %s!", word, word_count, event.event_id) counts.setdefault(word, 0) counts[word] += word_count for word, count in counts.items(): key = "june_wordcount_%s" % word self.log.debug("Fetching redis key %r", key) stored = await self.bot.redis.get(key) stored = int(stored) if stored else 0 stored += count await self.bot.redis.set(key, count) self.log.debug("June has now said %r %d times", word, stored) @niobot.command(name="june-word-count", hidden=True) async def june_word_count( self, ctx: niobot.Context, raw: bool = False ): keys = {} lines = [] if raw: lines.append("```md") for key in await self.bot.redis.keys("june_wordcount_*"): key = key.decode() value = await self.bot.redis.get(key) value = int(value) if raw: lines.append(f"* {key}: {value}") else: keys[key[15:]] = value for key, count in keys.items(): lines.append(f"* {key}: {count:,}") text = "\n".join(lines) if raw: text += "\n```" return await ctx.respond(text)