Telebot — Example Code

@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
bot.reply_to(message, "Howdy, how are you doing?")
@bot.message_handler(func=lambda message: True)
def echo_all(message):
bot.reply_to(message, message.text)
bot.infinity_polling(skip_pending=True)# Skip pending skips old updates
import time, threading, schedule
from telebot import TeleBot
API_TOKEN = '<api_token>'
bot = TeleBot(API_TOKEN)
@bot.message_handler(commands=['help', 'start'])
def send_welcome(message):
bot.reply_to(message, "Hi! Use /set <seconds> to set a timer")
def beep(chat_id) -> None:
"""Send the beep message."""
bot.send_message(chat_id, text='Beep!')
@bot.message_handler(commands=['set'])
def set_timer(message):
args = message.text.split()
if len(args) > 1 and args[1].isdigit():
sec = int(args[1])
schedule.every(sec).seconds.do(beep, message.chat.id).tag(message.chat.id)
else:
bot.reply_to(message, 'Usage: /set <seconds>')
@bot.message_handler(commands=['unset'])
def unset_timer(message):
schedule.clear(message.chat.id)
if __name__ == '__main__':
threading.Thread(target=bot.infinity_polling, name='bot_infinity_polling', daemon=True).start()
while True:
schedule.run_pending()
time.sleep(1)
ret_msg = bot.send_voice(CHAT_ID, open('tests/test_data/record.ogg', 'rb')) file_info = bot.get_file(ret_msg.voice.file_id) downloaded_file = bot.download_file(file_info.file_path) with open('new_file.ogg', 'wb') as new_file:
new_file.write(downloaded_file)
def extract_unique_code(text):
# Extracts the unique_code from the sent /start command.
return text.split()[1] if len(text.split()) > 1 else None
def in_storage(unique_code):
# (pseudo-code) Should check if a unique code exists in storage
return True
def get_username_from_storage(unique_code):
# (pseudo-code) Does a query to the storage, retrieving the associated username
# Should be replaced by a real database-lookup.
return "ABC" if in_storage(unique_code) else None
def save_chat_id(chat_id, username):
# (pseudo-code) Save the chat_id->username to storage
# Should be replaced by a real database query.
pass
@bot.message_handler(commands=['start'])
def send_welcome(message):
unique_code = extract_unique_code(message.text)
if unique_code: # if the '/start' command contains a unique_code
username = get_username_from_storage(unique_code)
if username: # if the username exists in our database
save_chat_id(message.chat.id, username)
reply = "Hello {0}, how are you?".format(username)
else:
reply = "I have no clue who you are..."
else:
reply = "Please visit me via a provided URL from the website."
bot.reply_to(message, reply)

More examples

Code Template

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store