repl_driver.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. from datetime import datetime
  2. import asyncio
  3. import rollbot
  4. from rollbot.injection import ArgList, Lazy, Database, Data, Args
  5. @rollbot.initialize_data
  6. class MyCounter:
  7. one: int = 0
  8. two: int = 0
  9. class MyBot(rollbot.Rollbot[str]):
  10. def read_config(self, key):
  11. return key
  12. def parse(self, raw):
  13. return rollbot.Message(
  14. origin_id="REPL",
  15. channel_id=".",
  16. sender_id=".",
  17. timestamp=datetime.now(),
  18. origin_admin=True,
  19. channel_admin=True,
  20. text=raw,
  21. attachments=[],
  22. )
  23. async def respond(self, res):
  24. print(res, flush=True)
  25. async def goodbye_command(message, context):
  26. await context.respond(rollbot.Response.from_message(message, "Goodbye!"))
  27. async def count_command(message, context):
  28. args = message.text.split("count", maxsplit=1)[1].strip().split()
  29. name = args[0] if len(args) > 0 else "main"
  30. async with context.database() as db:
  31. await db.execute(
  32. "INSERT INTO counter VALUES (?, 1) \
  33. ON CONFLICT (name) DO UPDATE SET count=count + 1",
  34. (name,),
  35. )
  36. await db.commit()
  37. async with db.execute("SELECT count FROM counter WHERE name = ?", (name,)) as cursor:
  38. res = (await cursor.fetchone())[0]
  39. await context.respond(rollbot.Response.from_message(message, f"{name} = {res}"))
  40. @rollbot.as_command
  41. async def count2(args: ArgList, connect: Lazy(Database)):
  42. name = args[0] if len(args) > 0 else "main"
  43. db = await connect()
  44. await db.execute(
  45. "INSERT INTO counter VALUES (?, 1) \
  46. ON CONFLICT (name) DO UPDATE SET count=count + 2",
  47. (name,),
  48. )
  49. await db.commit()
  50. async with db.execute("SELECT count FROM counter WHERE name = ?", (name,)) as cursor:
  51. res = (await cursor.fetchone())[0]
  52. return f"{name} = {res}"
  53. @rollbot.as_command
  54. async def count3(counter: Data(MyCounter).For(Args), store: Data(MyCounter), args: Args):
  55. counter.one += 1
  56. counter.two += 2
  57. await store.save(args, counter)
  58. return f"{args} = {counter}"
  59. @rollbot.on_startup
  60. async def make_table(context):
  61. async with context.database() as db:
  62. await db.execute(
  63. "CREATE TABLE IF NOT EXISTS counter ( \
  64. name TEXT NOT NULL PRIMARY KEY, \
  65. count INTEGER NOT NULL DEFAULT 0 \
  66. );"
  67. )
  68. await db.commit()
  69. @rollbot.on_shutdown
  70. async def shutdown(context):
  71. await context.respond(rollbot.Response(origin_id="REPL", channel_id=".", text="Shutting down!"))
  72. @rollbot.as_command
  73. def simple():
  74. return "Simple!"
  75. @rollbot.as_command
  76. def generator():
  77. yield "This is"
  78. yield "a generator!"
  79. @rollbot.as_command
  80. async def coroutine():
  81. await asyncio.sleep(1.0)
  82. return "Here's a coroutine!"
  83. @rollbot.as_command
  84. async def asyncgen():
  85. yield "This is"
  86. await asyncio.sleep(0.5)
  87. yield "an async"
  88. await asyncio.sleep(0.5)
  89. yield "generator!"
  90. config = rollbot.get_command_config().extend(
  91. rollbot.CommandConfiguration(
  92. commands={
  93. "goodbye": goodbye_command,
  94. "count": count_command,
  95. },
  96. call_and_response={
  97. "hello": "Hello!",
  98. },
  99. aliases={
  100. "hi": "hello",
  101. "bye": "goodbye",
  102. },
  103. bangs=("/",),
  104. )
  105. )
  106. bot = MyBot(config, "/tmp/my.db")
  107. async def run():
  108. await bot.on_startup()
  109. try:
  110. while True:
  111. await bot.on_message(input("> "))
  112. except EOFError:
  113. pass
  114. await bot.on_shutdown()
  115. asyncio.run(run())