Queer European MD passionate about IT

a_simple_bot.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. """This example script shows how to develop a simple bot with davtelepot.
  2. 1. Install davtelepot
  3. ```bash
  4. # Create a new python virtual environment
  5. pip -m venv env
  6. # Activate the virtual environment
  7. source env/bin/activate
  8. # Install davtelepot library in this environment
  9. pip install davtelepot
  10. # Run the current script within this environment
  11. python a_simple_bot.py
  12. ```
  13. 2. To run your bot, you will need a bot token. You can get up to 20 bot tokens
  14. from https://t.me/botfather
  15. 3. This script will look for your bot token in a gitignored `secrets.py` file
  16. in the same folder as the current script. If no `secrets` module is found,
  17. user will be prompted at runtime for a token, and the entry will be stored
  18. in `secrets.py` for later use.
  19. 4. Standard library, third party and project modules will be imported, and
  20. `logging` preferences set. You are free to edit these settings, e.g. adding
  21. one or more file and error loggers or setting different levels.
  22. 5. `simple_bot` is an instance of `davtelepot.bot.Bot` class.
  23. To instantiate a bot you need to provide at least a Telegram bot API token,
  24. and you may also provide a path to a database (if no path is provided,
  25. a `./bot.db` SQLite database will be used).
  26. 6. `initialize_bot` function is defined and called on `simple_bot`. It assigns
  27. commands, parsers, callback and inline query handlers to the bot.
  28. 7. `Bot.run()` method is called, causing the script to hang while asynchronous
  29. tasks run checking for updates and routing them to get and send replies.
  30. Send a KeyboardInterrupt (ctrl+C) to stop the bot.
  31. """
  32. # Standard library modules
  33. import logging
  34. import os
  35. import sys
  36. # Third party modules
  37. try:
  38. from davtelepot.bot import Bot
  39. from davtelepot.utilities import (
  40. get_cleaned_text, make_inline_keyboard, make_button
  41. )
  42. except ImportError:
  43. logging.error(
  44. "Please install davtelepot library.\n"
  45. "Using a python virtual environment is advised.\n\n"
  46. "```bash\n"
  47. "pip -m venv env\n"
  48. "env/bin/pip install davtelepot\n"
  49. "env/bin/python davtelepot/examples/a_simple_bot.py"
  50. "```"
  51. )
  52. sys.exit(1)
  53. # Get path of current script
  54. path = os.path.dirname(os.path.abspath(__file__))
  55. def initialize_bot(bot):
  56. """Take a bot and set commands."""
  57. bot.set_callback_data_separator('|')
  58. @bot.command(command='foo', aliases=['Foo'], show_in_keyboard=True,
  59. description="Reply 'bar' to 'foo'",
  60. authorization_level='everybody')
  61. async def foo_command(bot, update, user_record):
  62. return 'Bar!'
  63. def is_bar_text_message(text):
  64. return text.startswith('bar')
  65. @bot.parser(condition=is_bar_text_message,
  66. description='Reply Foo to users who write Bar',
  67. authorization_level='everybody',
  68. argument='text')
  69. async def bar_parser(bot, update):
  70. text_except_foo = get_cleaned_text(update, bot, ['bar'])
  71. return f"Foo!\n{text_except_foo}"
  72. def get_keyboard(chosen_button=-1):
  73. return make_inline_keyboard(
  74. [
  75. make_button(
  76. prefix='button:///',
  77. delimiter='|',
  78. data=[i],
  79. text=f"{'✅' if chosen_button == i else '☑️'} Button #{i}"
  80. )
  81. for i in range(1, 13)
  82. ],
  83. 3
  84. )
  85. @bot.command(command='buttons')
  86. async def buttons_command():
  87. return dict(
  88. text="Press a button!",
  89. reply_markup=get_keyboard()
  90. )
  91. @bot.button(prefix='button:///', separator='|',
  92. authorization_level='everybody')
  93. async def buttons_button(bot, update, user_record, data):
  94. button_number = data[0]
  95. return dict(
  96. edit=dict(
  97. text=f"You pressed button #{button_number}",
  98. reply_markup=get_keyboard(button_number)
  99. )
  100. )
  101. def starts_with_a(text):
  102. return text.startswith('a')
  103. @bot.query(
  104. condition=starts_with_a,
  105. description='Mirror query text if it starts with letter `a`',
  106. authorization_level='everybody'
  107. )
  108. async def inline_query(bot, update, user_record):
  109. return dict(
  110. type='article',
  111. id=10,
  112. title="Click here to send your query text as a message.",
  113. input_message_content=dict(
  114. message_text=update['query']
  115. )
  116. )
  117. bot.set_default_inline_query_answer(
  118. dict(
  119. type='article',
  120. id=0,
  121. title="Start query text with `a` to mirror it.",
  122. input_message_content=dict(
  123. message_text="This query does not start with `a`."
  124. )
  125. )
  126. )
  127. bot.set_unknown_command_message(
  128. "<b>Currently supported features</b>\n\n"
  129. "- /foo (or text starting with `foo`): replies `Bar!`.\n"
  130. "- Text starting with `bar`: replies `Foo!` followed by the rest of "
  131. "text in your bar-starting message.\n"
  132. "- /buttons demonstrates the use of buttons.\n"
  133. "- Inline queries starting with letter `a` will be mirrored as text "
  134. "messages. To use this feature, try writing <code>@{bot.name} "
  135. "your_text_here</code>"
  136. )
  137. def _main():
  138. # Import or prompt user for bot token
  139. try:
  140. from secrets import simple_bot_token
  141. except ImportError:
  142. simple_bot_token = input("Enter bot token:\t\t")
  143. with open(
  144. f'{path}/secrets.py',
  145. 'a' # Append to file, create it if it does not exist
  146. ) as secrets_file:
  147. secrets_file.write(f'simple_bot_token = "{simple_bot_token}"\n')
  148. # Set logging preferences
  149. log_formatter = logging.Formatter(
  150. "%(asctime)s [%(module)-15s %(levelname)-8s] %(message)s",
  151. style='%'
  152. )
  153. root_logger = logging.getLogger()
  154. root_logger.setLevel(logging.DEBUG)
  155. consoleHandler = logging.StreamHandler()
  156. consoleHandler.setFormatter(log_formatter)
  157. consoleHandler.setLevel(logging.DEBUG)
  158. root_logger.addHandler(consoleHandler)
  159. # Instantiate, initialize and make `simple_bot` run.
  160. simple_bot = Bot(token=simple_bot_token, database_url=f"{path}/bot.db")
  161. initialize_bot(simple_bot)
  162. logging.info("Send a KeyboardInterrupt (ctrl+C) to stop bots.")
  163. Bot.run()
  164. if __name__ == '__main__':
  165. _main()