Ответы пользователя по тегу Боты
  • Как можно обновлять текст сообщения?

    deepblack
    @deepblack Куратор тега Python
    Посмотри как это сделано сдесь:
    spoiler
    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()
    Ответ написан
    Комментировать
  • Как создать кнопку telegram?

    deepblack
    @deepblack Куратор тега Python
    Пример под спойлером
    spoiler
    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()


    Я документации не понимать

    По английски читать не умеешь, что-ли?
    Ответ написан
  • Vk Api выдаёт ошибку. Как исправить?

    deepblack
    @deepblack Куратор тега Python
    Ясно ведь написано что chat_id не указан.
    Ответ написан
    2 комментария
  • Номер телефона, как ссылка в telegram bot?

    deepblack
    @deepblack Куратор тега Python
    spoiler
    https://stackoverflow.com/questions/40590683/how-t...
    bot.send_message(
        chat_id,
        "Example text with a phone [+79991234567](tel:+79991234567)", 
        parse_mode='Markdown'
    )


    Сообщение должно быть < 200 символов, номер как ссылка только на мобильном устройстве.

    upd:

    Это работает

    Номер отправляю простым текстом5d47fef5ba3ba100526303.jpeg
    Ответ написан
    2 комментария
  • Как реализовать реферальную систему в Telegram боте?

    deepblack
    @deepblack Куратор тега Python
    Как реализовать реферальную систему в Telegram боте?

    Тут хотелось увидеть в чём возникла сложность? Снова прийдется гадать.

    Внимательно документацию почитать для начала.
    https://core.telegram.org/bots#deep-linking
    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


    Далее посмотреть в примерах:
    deep_linking.py
    Ответ написан
    2 комментария
  • Как после ввода команды, получить текст?

    deepblack
    @deepblack Куратор тега Python
    я читал этот раздел. Мне надо, чтобы бот отвечал именно так после команды /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")
    Ответ написан
    1 комментарий
  • Как сделать бота VK, который получает цифровой ID из ссылки и отправляет пользователю?

    deepblack
    @deepblack Куратор тега Python
    У VK API есть метод https://vk.com/dev/users.get

    1. скармливаешь ему screen_name
    2. получаешь ID пользователя и дополнительный поля (если надо)
    5ce61aa65c5d4689497433.png
    spoiler
    Тут дел минут на десять, из которых 5 это выпить кофе
    Ответ написан
    4 комментария
  • Как сделать жирный шрифт в Telegram боте?

    deepblack
    @deepblack
    Вот для примера фрагмент кода:
    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")
    Ответ написан
    3 комментария