repl_driver.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. from datetime import datetime
  2. from logging import Logger
  3. import asyncio
  4. import rollbot
  5. from rollbot.injection import ArgList, Lazy, Database, Data, Args, Arg, Subcommand
  6. @rollbot.initialize_data
  7. class MyCounter:
  8. one: int = 0
  9. two: int = 0
  10. class MyBot(rollbot.Rollbot[str]):
  11. def read_config(self, key):
  12. return key
  13. def parse(self, raw):
  14. return rollbot.Message(
  15. origin_id="REPL",
  16. channel_id=".",
  17. sender_id=".",
  18. timestamp=datetime.now(),
  19. origin_admin=True,
  20. channel_admin=True,
  21. text=raw,
  22. attachments=[],
  23. )
  24. async def respond(self, res):
  25. print(res, flush=True)
  26. async def goodbye_command(message, context):
  27. await context.respond(rollbot.Response.from_message(message, "Goodbye!"))
  28. async def count_command(message, context):
  29. args = message.text.split("count", maxsplit=1)[1].strip().split()
  30. name = args[0] if len(args) > 0 else "main"
  31. async with context.database() as db:
  32. await db.execute(
  33. "INSERT INTO counter VALUES (?, 1) \
  34. ON CONFLICT (name) DO UPDATE SET count=count + 1",
  35. (name,),
  36. )
  37. await db.commit()
  38. async with db.execute("SELECT count FROM counter WHERE name = ?", (name,)) as cursor:
  39. res = (await cursor.fetchone())[0]
  40. await context.respond(rollbot.Response.from_message(message, f"{name} = {res}"))
  41. @rollbot.as_command
  42. async def count2(name: Arg(0, required=False, default="main"), connect: Lazy(Database)):
  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.as_command("count.")
  70. async def count_improved(
  71. subc: Subcommand,
  72. name: Subcommand.Arg(0, required=False, default="main"),
  73. counter: Data(MyCounter).For(Subcommand.Arg(0, required=False, default="main")),
  74. store: Data(MyCounter),
  75. log: Logger,
  76. ):
  77. if subc.name == "up":
  78. counter.one += 1
  79. counter.two += 2
  80. elif subc.name == "down":
  81. counter.one -= 1
  82. counter.two -= 2
  83. elif subc.name == "show":
  84. yield f"{name} = {counter}"
  85. log.info(f"Saving {counter} under {name}")
  86. await store.save(name, counter)
  87. @rollbot.on_startup
  88. async def make_table(context):
  89. async with context.database() as db:
  90. await db.execute(
  91. "CREATE TABLE IF NOT EXISTS counter ( \
  92. name TEXT NOT NULL PRIMARY KEY, \
  93. count INTEGER NOT NULL DEFAULT 0 \
  94. );"
  95. )
  96. await db.commit()
  97. @rollbot.on_shutdown
  98. async def shutdown(context):
  99. await context.respond(rollbot.Response(origin_id="REPL", channel_id=".", text="Shutting down!"))
  100. @rollbot.as_command
  101. def simple():
  102. return "Simple!"
  103. @rollbot.as_command
  104. def generator():
  105. yield "This is"
  106. yield "a generator!"
  107. @rollbot.as_command
  108. async def coroutine():
  109. await asyncio.sleep(1.0)
  110. return "Here's a coroutine!"
  111. @rollbot.as_command
  112. async def asyncgen():
  113. yield "This is"
  114. await asyncio.sleep(0.5)
  115. yield "an async"
  116. await asyncio.sleep(0.5)
  117. yield "generator!"
  118. config = rollbot.get_command_config().extend(
  119. rollbot.CommandConfiguration(
  120. commands={
  121. "goodbye": goodbye_command,
  122. "count": count_command,
  123. },
  124. call_and_response={
  125. "hello": "Hello!",
  126. },
  127. aliases={
  128. "hi": "hello",
  129. "bye": "goodbye",
  130. },
  131. bangs=("/",),
  132. )
  133. )
  134. bot = MyBot(config, "/tmp/my.db")
  135. async def run():
  136. await bot.on_startup()
  137. try:
  138. while True:
  139. await bot.on_message(input("> "))
  140. except EOFError:
  141. pass
  142. finally:
  143. await bot.on_shutdown()
  144. asyncio.run(run())