import os
import logging
from pathlib import Path
from functools import wraps
from dotenv import load_dotenv
from utils import Video, BadLink
from telegram import InlineKeyboardMarkup, ChatAction
from telegram.ext import Updater, CallbackQueryHandler, MessageHandler, Filters
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)
def send_action(action):
def decorator(func):
@wraps(func)
def command_func(update, context, *args, **kwargs):
context.bot.send_chat_action(chat_id=update.effective_message.chat_id, action=action)
return func(update, context, *args, **kwargs)
return command_func
return decorator
send_typing_action = send_action(ChatAction.TYPING)
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
@send_typing_action
def get_format(update, context):
logger.info("from {}: {}".format(update.message.chat_id, update.message.text))
try:
video = Video(update.message.text, init_keyboard=True)
except BadLink:
update.message.reply_text("Your link is not valid")
else:
reply_markup = InlineKeyboardMarkup(video.keyboard)
update.message.reply_text('Choose format:', reply_markup=reply_markup)
@send_typing_action
def download_desired_format(update, context):
query = update.callback_query
resolution_code, link, merge_formats = query.data.split(' ', 2)
print('chat_id: ', query.message.chat_id)
print('Merge formats: ', merge_formats)
query.edit_message_text(text="Downloading")
video = Video(link)
video.download(resolution_code, merge_formats)
with video.send() as files:
for f in files:
context.bot.send_document(chat_id=query.message.chat_id, document=open(f, 'rb'))
updater = Updater(token=os.getenv("TG_BOT_TOKEN"), use_context=True)
updater.dispatcher.add_handler(MessageHandler(Filters.text, get_format))
updater.dispatcher.add_handler(CallbackQueryHandler(download_desired_format))
updater.start_polling()
updater.idle()
import logging
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
def start(update, context):
keyboard = [[InlineKeyboardButton("Option 1", callback_data='1'),
InlineKeyboardButton("Option 2", callback_data='2')],
[InlineKeyboardButton("Option 3", callback_data='3')]]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text('Please choose:', reply_markup=reply_markup)
def button(update, context):
query = update.callback_query
query.edit_message_text(text="Selected option: {}".format(query.data))
def help(update, context):
update.message.reply_text("Use /start to test this bot.")
def error(update, context):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, context.error)
def main():
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True)
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CallbackQueryHandler(button))
updater.dispatcher.add_handler(CommandHandler('help', help))
updater.dispatcher.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until the user presses Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT
updater.idle()
if __name__ == '__main__':
main()
Я документации не понимать
bot.send_message(
chat_id,
"Example text with a phone [+79991234567](tel:+79991234567)",
parse_mode='Markdown'
)
Как реализовать реферальную систему в Telegram боте?
Deep linking
Telegram bots have a deep linking mechanism, that allows for passing additional parameters to the bot on startup. It could be a command that launches the bot — or an auth token to connect the user's Telegram account to their account on some external service.
Each bot has a link that opens a conversation with it in Telegram — https://telegram.me/. You can add the parameters start or startgroup to this link, with values up to 64 characters long. For example:https://telegram.me/triviabot?startgroup=test
я читал этот раздел. Мне надо, чтобы бот отвечал именно так после команды /cup. А просто текст он должен обрабатывать по другому.
@bot.message_handler(commands=['cup'])
def command_start(m):
... # тут твой код
# default handler for every other text
@bot.message_handler(func=lambda message: True, content_types=['text'])
def command_default(m):
# this is the standard reply to a normal message
bot.send_message(m.chat.id, "I don't understand \"" + m.text + "\"\nMaybe try the help page at /help")
def test_send_message_with_markdown(self):
tb = telebot.TeleBot(TOKEN)
markdown = """
*bold text*
_italic text_
[text](URL)
"""
ret_msg = tb.send_message(CHAT_ID, markdown, parse_mode="Markdown")
assert ret_msg.message_id
bot.send_message(CHAT_ID, "*Здесь должен быть жирный шрифт*", parse_mode= "Markdown")