xxxxxxxxxx
import telebot
import time
bot = telebot.TeleBot('TOKEN')
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):
# Should check if a unique code exists in storage
return True
def get_username_from_storage(unique_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):
# 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)
bot.polling()
while True:
time.sleep(0)
xxxxxxxxxx
import logging
import telegram
from telegram.ext import Updater, CommandHandler
# Logging configuration
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
# Create an Updater object
updater = Updater(token='<YOUR_TELEGRAM_TOKEN>', use_context=True)
# Create a dispatcher
dispatcher = updater.dispatcher
# Create a command handler
def start(update, context):
context.bot.send_message(chat_id=update.effective_chat.id,
text="Hi! I'm OTPBot. I can generate one-time passwords for you.")
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)
# Create a function to generate OTP
def generate_otp(length):
"""Generate a one-time password of given length.
Args:
length (int): Length of the OTP to be generated.
Returns:
str: Generated OTP.
"""
import random
import string
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))
# Create a command handler to generate OTP
def generate(update, context):
"""Generate a one-time password of given length.
Args:
update (telegram.Update): An update from Telegram.
context (telegram.ext.CallbackContext): Context of the update.
"""
# Get the length of OTP from the user
length = int(context.args[0])
# Generate the OTP
otp = generate_otp(length)
# Send the OTP to the user
context.bot.send_message(chat_id=update.effective_chat.id,
text=f"Your OTP is: {otp}")
generate_handler = CommandHandler('generate', generate)
dispatcher.add_handler(generate_handler)
# Start the bot
updater.start_polling()