repl_driver.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. @rollbot.on_startup
  34. async def make_table(context):
  35. async with context.database() as db:
  36. await db.execute("CREATE TABLE IF NOT EXISTS counter ( \
  37. name TEXT NOT NULL PRIMARY KEY, \
  38. count INTEGER NOT NULL DEFAULT 0 \
  39. );")
  40. await db.commit()
  41. @rollbot.on_shutdown
  42. async def shutdown(context):
  43. await context.respond(rollbot.Response(origin_id="REPL", channel_id=".", text="Shutting down!"))
  44. @rollbot.as_command
  45. def simple():
  46. return "Simple!"
  47. @rollbot.as_command
  48. def generator():
  49. yield "This is"
  50. yield "a generator!"
  51. @rollbot.as_command
  52. async def coroutine():
  53. await asyncio.sleep(1.0)
  54. return "Here's a coroutine!"
  55. @rollbot.as_command
  56. async def asyncgen():
  57. yield "This is"
  58. await asyncio.sleep(0.5)
  59. yield "an async"
  60. await asyncio.sleep(0.5)
  61. yield "generator!"
  62. config = rollbot.get_command_config().extend(
  63. rollbot.CommandConfiguration(
  64. commands={
  65. "goodbye": goodbye_command,
  66. "count": count_command,
  67. },
  68. call_and_response={
  69. "hello": "Hello!",
  70. },
  71. aliases={
  72. "hi": "hello",
  73. "bye": "goodbye",
  74. },
  75. bangs=("/",),
  76. )
  77. )
  78. bot = MyBot(config, "/tmp/my.db")
  79. async def run():
  80. await bot.on_startup()
  81. try:
  82. while True:
  83. await bot.on_message(input("> "))
  84. except EOFError:
  85. pass
  86. await bot.on_shutdown()
  87. asyncio.run(run())