repl_driver.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. from datetime import datetime
  2. import asyncio
  3. import rollbot
  4. class MyBot(rollbot.Rollbot[str]):
  5. def read_config(self, key):
  6. return key
  7. def parse(self, raw):
  8. return rollbot.Message(
  9. origin_id="REPL",
  10. channel_id=".",
  11. sender_id=".",
  12. timestamp=datetime.now(),
  13. origin_admin=True,
  14. channel_admin=True,
  15. text=raw,
  16. attachments=[],
  17. )
  18. async def respond(self, res):
  19. print(res, flush=True)
  20. async def goodbye_command(message, context):
  21. await context.respond(rollbot.Response.from_message(message, "Goodbye!"))
  22. async def count_command(message, context):
  23. args = message.text.split("count", maxsplit=1)[1].strip().split()
  24. name = args[0] if len(args) > 0 else "main"
  25. async with context.database() as db:
  26. await db.execute("INSERT INTO counter VALUES (?, 1) \
  27. ON CONFLICT (name) DO \
  28. UPDATE SET count=count + 1", (name,))
  29. await db.commit()
  30. async with db.execute("SELECT count FROM counter WHERE name = ?", (name,)) as cursor:
  31. res = (await cursor.fetchone())[0]
  32. await context.respond(rollbot.Response.from_message(message, f"{name} = {res}"))
  33. async def make_table(context):
  34. async with context.database() as db:
  35. await db.execute("CREATE TABLE IF NOT EXISTS counter ( \
  36. name TEXT NOT NULL PRIMARY KEY, \
  37. count INTEGER NOT NULL DEFAULT 0 \
  38. );")
  39. await db.commit()
  40. config = rollbot.CommandConfiguration(
  41. commands={
  42. "goodbye": goodbye_command,
  43. "count": count_command,
  44. },
  45. call_and_response={
  46. "hello": "Hello!",
  47. },
  48. aliases={
  49. "hi": "hello",
  50. "bye": "goodbye",
  51. },
  52. bangs=("/",),
  53. startup=[make_table],
  54. )
  55. bot = MyBot(config, "/tmp/my.db")
  56. async def run():
  57. await bot.on_startup()
  58. try:
  59. while True:
  60. await bot.on_message(input("> "))
  61. except EOFError:
  62. pass
  63. await bot.on_shutdown()
  64. asyncio.run(run())