- First of all, you require pyTelegramBotAPI library;
- Then, you want to add @BotFather in Telegram and follow the instructure #6. You need to obtain the bot token which is a unique set of letters and digits for your bot, just like a codename. After you have registered a bot via @BotFather, it will give you the token.
Actually, the token is the only thing you need to create any bot you want. The codes for the bot like yours should follow the same logic structure:
# -*- coding: utf-8 -*-
import telebot # importing pyTelegramBotAPI library
import time
import sys
bot = telebot.Telebot(token='YOUR API TOKEN') # supply your future bot with the token you have received
@bot.message_handler(commands=['define', 'Define'])
def echo_msg(message):
echo = bot.send_message(chat_id=message.chat.it,
text='What word would you want me to extract, sir?')
bot.register_next_step_handler(message=echo, callback=extract_msg)
def extract_msg(message):
msg.append(message.text)
print(msg)
def main_loop():
bot.polling(none_stop=True)
while True:
time.sleep(1)
if __name__ == '__main__':
try:
main_loop()
except KeyboardInterrupt:
print(sys.stderr '\nExiting by user request'\n')
sys.exit(0)
Okay, each bot requires a message_handler
to process the incoming information.
In your case, it is a command that triggers the bot to ask for a word to extract into a list. If you do not define bot.register_next_step_handler()
, this command will not do any action at all (except the fact it asks for a word).
The function extract_msg()
appends the next word written by a user and prints out the msg
list into your console.
The function main_loop()
runs the bot until suspension and provokes it to idle for a second after each word extraction. To stop the bot, press Ctrl + C.
I hope that suffices. The next step would be to track the person who types /define
or /Define
and extract his/her word request. Also, it would be better to make msg
list more descriptive, or implement absolutely different extraction method. This one is simply informative and hardly applicable in practice.