repl_driver.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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.as_command
  60. async def count6(counters: Data(MyCounter)):
  61. async for (key, counter) in counters.all(one=6):
  62. yield f"{key} = {counter}"
  63. async for (key, counter) in counters.all(two=6):
  64. yield f"{key} = {counter}"
  65. @rollbot.as_command
  66. async def lscounters(counters: Data(MyCounter)):
  67. async for (key, counter) in counters.all():
  68. yield f"{key} = {counter}"
  69. @rollbot.on_startup
  70. async def make_table(context):
  71. async with context.database() as db:
  72. await db.execute(
  73. "CREATE TABLE IF NOT EXISTS counter ( \
  74. name TEXT NOT NULL PRIMARY KEY, \
  75. count INTEGER NOT NULL DEFAULT 0 \
  76. );"
  77. )
  78. await db.commit()
  79. @rollbot.on_shutdown
  80. async def shutdown(context):
  81. await context.respond(rollbot.Response(origin_id="REPL", channel_id=".", text="Shutting down!"))
  82. @rollbot.as_command
  83. def simple():
  84. return "Simple!"
  85. @rollbot.as_command
  86. def generator():
  87. yield "This is"
  88. yield "a generator!"
  89. @rollbot.as_command
  90. async def coroutine():
  91. await asyncio.sleep(1.0)
  92. return "Here's a coroutine!"
  93. @rollbot.as_command
  94. async def asyncgen():
  95. yield "This is"
  96. await asyncio.sleep(0.5)
  97. yield "an async"
  98. await asyncio.sleep(0.5)
  99. yield "generator!"
  100. config = rollbot.get_command_config().extend(
  101. rollbot.CommandConfiguration(
  102. commands={
  103. "goodbye": goodbye_command,
  104. "count": count_command,
  105. },
  106. call_and_response={
  107. "hello": "Hello!",
  108. },
  109. aliases={
  110. "hi": "hello",
  111. "bye": "goodbye",
  112. },
  113. bangs=("/",),
  114. )
  115. )
  116. bot = MyBot(config, "/tmp/my.db")
  117. async def run():
  118. await bot.on_startup()
  119. try:
  120. while True:
  121. await bot.on_message(input("> "))
  122. except EOFError:
  123. pass
  124. finally:
  125. await bot.on_shutdown()
  126. asyncio.run(run())