当前位置: 首页>>代码示例>>Python>>正文


Python Bot.send_message方法代码示例

本文整理汇总了Python中telegram.Bot.send_message方法的典型用法代码示例。如果您正苦于以下问题:Python Bot.send_message方法的具体用法?Python Bot.send_message怎么用?Python Bot.send_message使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在telegram.Bot的用法示例。


在下文中一共展示了Bot.send_message方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: start

# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import send_message [as 别名]
def start(bot: Bot, update: Update):
    users_handler(bot, update)
    message: Message = update.message
    with menus_lock:
        if message.chat_id not in menus:
            menus[message.chat_id] = Menu()
        else:
            # todo remove old keyboard and replace with the new one?
            pass
        menu = menus[message.chat_id]
    api = RpApi.get_instance(settings.Settings().rp_username, settings.Settings().rp_pass)
    response = api.get_telegram_link(update.effective_user.id)
    rp_acc = response.data
    if rp_acc is None:
        user: User = update.effective_user
        api.send_telegram_user(user.id, user.first_name, user.last_name, user.username)
        bot.send_message(update.effective_chat.id, 'Je telegram account is nog niet gelinkt.'
                                                   'Vraag aan de homebase of ze dat willen doen. '
                                                   'En zeg daarna /start.',
                         reply_to_message_id=update.effective_message.message_id)
    text, buttons = menu.get_next_buttons(update, '0', rp_acc)
    keyboard = [[button] for button in buttons]
    reply_markup = InlineKeyboardMarkup(keyboard)
    if update.effective_chat.type == Chat.PRIVATE:
        keyboard = ReplyKeyboardMarkup([[KeyboardButton('/start met het laten zien van het menu')]
                                   , [KeyboardButton('verstuur hunter locatie', request_location=True)]])
    else:
        keyboard = ReplyKeyboardMarkup([])
    bot.send_message(update.effective_chat.id, welcome_message, reply_markup=keyboard)
    message.reply_text(text, reply_markup=reply_markup)
开发者ID:RSDT,项目名称:bot2,代码行数:32,代码来源:menu.py

示例2: delete

# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import send_message [as 别名]
def delete(bot: Bot, update: Update):
    if not DELETE:
        return

    global data_set
    chat_id = update.message.chat_id
    user = data_set.participants[update.message.chat_id]
    user.active_ = False
    user.delete_participant()

    try:
        os.remove('survey/data_incomplete/' + str(user.chat_id_) + '.csv')
    except OSError:
        pass

    try:
        os.remove('survey/data_complete/' + str(user.chat_id_) + '.csv')
    except OSError:
        pass

    del data_set.participants[update.message.chat_id]
    try:
        bot.send_message(chat_id=chat_id, text="Successfully deleted DB entry and user data. To restart enter /start")
    except TelegramError as error:
        if error.message == 'Unauthorized':
            user.pause()
开发者ID:philippfeldner,项目名称:diary-survey-bot,代码行数:28,代码来源:diary-survey-bot.py

示例3: __init__

# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import send_message [as 别名]
class TelegramBotAlert:


    def __init__(self):
        self.model = Model()
        config = configparser.ConfigParser()
        config.read('settings.ini')

        self.__list_of_chat_ids = self.model.get_chat_ids()
        self.__token = config.get("TELEGRAM", "token")
        self.__bot = Bot(token=self.__token)

    def create_alert_message(self, list_of_alredy_online_hosts, list_of_offline_hosts):
        message = ""

        if len(list_of_alredy_online_hosts) > 0:
            serialize_list_of_alredy_online_hosts = create_serialize_list_of_hosts(list_of_alredy_online_hosts)
            message += self.create_alert_message_with_alredy_online_hosts(serialize_list_of_alredy_online_hosts)

        if len(list_of_offline_hosts) > 0:
            serialize_list_of_offline_hosts = create_serialize_list_of_hosts(list_of_offline_hosts)
            message += self.create_alert_message_with_offline_hosts(serialize_list_of_offline_hosts)
        else:
            message += "Все узлы доступны."

        self.send_message(message)

    def create_alert_message_with_offline_hosts(self, list_of_hosts):
        message = "<b>Следующие узлы недоступны!</b>\n"
        for group in list_of_hosts:
            message += "\tГруппа: <i>{group_name}</i>\n".format(group_name=group)
            for host in list_of_hosts[group]:
                message += "\t\t{host}, {hostip}\n".format(host=host.get_name(), hostip=host.get_ip())
            message += "\n"
        return message

    def create_alert_message_with_alredy_online_hosts(self, list_of_hosts):
        message = "<b>Следующие узлы снова доступны:</b>\n"
        for group in list_of_hosts:
            message += "\tГруппа: <i>{group_name}</i>\n".format(group_name=group)
            for host in list_of_hosts[group]:
                message += "\t\t{host}, {hostip}\n".format(host=host.get_name(), hostip=host.get_ip())
            message += "\n"
        return message

    def send_message(self, message, send_to="All"):
        if send_to == "All":
            for chat_id in self.__list_of_chat_ids:
                self.__bot.send_message(chat_id=str(chat_id), text=message, parse_mode=ParseMode.HTML)
        else:
            self.__bot.send_message(chat_id=str(send_to), text=message, parse_mode=ParseMode.HTML)
开发者ID:shirolapov,项目名称:NetworkTester,代码行数:53,代码来源:bot.py

示例4: stop

# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import send_message [as 别名]
def stop(bot: Bot, update: Update):
    global data_set
    chat_id = update.message.chat_id
    user = data_set.participants[update.message.chat_id]
    user.pause()
    try:
        message = STOP_TEXT[user.language_]
        bot.send_message(chat_id=chat_id, text=message, reply_markup=ReplyKeyboardRemove())
    except KeyError:
        message = STOP_TEXT[DEFAULT_LANGUAGE]
        bot.send_message(chat_id=chat_id, text=message, reply_markup=ReplyKeyboardRemove())
    except TelegramError as error:
        if error.message == 'Unauthorized':
            user.pause()
开发者ID:philippfeldner,项目名称:diary-survey-bot,代码行数:16,代码来源:diary-survey-bot.py

示例5: start

# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import send_message [as 别名]
def start(bot: Bot, update: Update, job_queue):
    global data_set
    if update.message.chat_id not in data_set.participants:
        reply_markup = ReplyKeyboardMarkup(languages)
        try:
            bot.send_message(chat_id=update.message.chat_id, text="Please choose a language:", reply_markup=reply_markup)
        except TelegramError as error:
            if error.message == 'Unauthorized':
                return
        participant = Participant(update.message.chat_id)
        data_set.participants[update.message.chat_id] = participant
    else:
        user = data_set.participants[update.message.chat_id]
        # A user that has already completed the survey tries to do it again.
        if user.pointer_ == 0xFFFF:
            return
        continue_survey(user, bot, job_queue)
开发者ID:philippfeldner,项目名称:diary-survey-bot,代码行数:19,代码来源:diary-survey-bot.py

示例6: send_msg

# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import send_message [as 别名]
def send_msg(msg: str, bot: Bot = None, parse_mode: ParseMode = ParseMode.MARKDOWN) -> None:
    """
    Send given markdown message
    :param msg: message
    :param bot: alternative bot
    :param parse_mode: telegram parse mode
    :return: None
    """
    if not is_enabled():
        return

    bot = bot or _UPDATER.bot

    keyboard = [['/daily', '/profit', '/balance'],
                ['/status', '/status table', '/performance'],
                ['/count', '/start', '/stop', '/help']]

    reply_markup = ReplyKeyboardMarkup(keyboard)

    try:
        try:
            bot.send_message(
                _CONF['telegram']['chat_id'], msg,
                parse_mode=parse_mode, reply_markup=reply_markup
            )
        except NetworkError as network_err:
            # Sometimes the telegram server resets the current connection,
            # if this is the case we send the message again.
            logger.warning(
                'Got Telegram NetworkError: %s! Trying one more time.',
                network_err.message
            )
            bot.send_message(
                _CONF['telegram']['chat_id'], msg,
                parse_mode=parse_mode, reply_markup=reply_markup
            )
    except TelegramError as telegram_err:
        logger.warning('Got TelegramError: %s! Giving up on that message.', telegram_err.message)
开发者ID:enenn,项目名称:freqtrade,代码行数:40,代码来源:telegram.py

示例7: wol_command

# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import send_message [as 别名]
    def wol_command(self, bot: Bot, update: Update, args=[]):
        if len(args) != 1:
            bot.send_message(update.message.chat_id, text='Please specify computer name to wake up')
            return False

        mac_address = self.config.get(args[0])
        if mac_address:
            send_magic_package(mac_address)
            bot.send_message(update.message.chat_id, text='Computer will wake up soon')
        else:
            bot.send_message(update.message.chat_id, text='Sorry, invalid name')
开发者ID:Happi-cat,项目名称:untech-telegram-bot,代码行数:13,代码来源:__init__.py

示例8: unknown

# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import send_message [as 别名]
def unknown(bot: Bot, update):
    bot.send_message(
            chat_id=update.message.chat_id,
            text="Unknown Command.")
开发者ID:debiancn,项目名称:debiancnbot,代码行数:6,代码来源:bot.py

示例9: question_handler

# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import send_message [as 别名]
def question_handler(bot: Bot, update: Update, user_map: DataSet, job_queue: JobQueue):
    try:
        # Get the user from the dict and its question_set (by language)
        user = user_map.participants[update.message.chat_id]  # type: Participant

        # Case for very first question.
        if user.question_ == -1:
            user.set_active(True)
            user.set_language(update.message.text)
            user.set_block(0)
            q_set = user_map.return_question_set_by_language(user.language_)
            user.q_set_ = q_set
            current_day = q_set[0]["day"]
            user.set_day(current_day)
            user.set_block(0)
        elif user.q_idle_:
            q_set = user.q_set_
            # Get the matching question for the users answer.

            pointer = user.pointer_
            d_prev = q_set[pointer]

            b_prev = d_prev["blocks"][user.block_]
            q_prev = b_prev["questions"][user.question_]

            if not valid_answer(q_prev, update.message.text, user):
                user.set_q_idle(True)
                return
            # Storing the answer and moving on the next question
            store_answer(user, update.message.text, q_prev, job_queue)
            user.set_q_idle(False)
        else:
            # User has send something without being asked a question.
            return
    except KeyError as error:
        print(error)
        return

    if not user.active_:
        return

    message, question = find_next_question(user)
    if question is not None:
        message = question["text"]
        q_keyboard = get_keyboard(question["choice"], user)
        try:
            bot.send_message(chat_id=user.chat_id_, text=message, reply_markup=q_keyboard)
            debug(flag="MSG", text=str(user.chat_id_) + ": " + message + "\n")
        except TelegramError as error:
            if error.message == 'Unauthorized':
                user.pause()

        user.set_q_idle(True)
    elif user.auto_queue_ is False:
        user.block_complete_ = True
        next_day = user.set_next_block()
        if next_day is None:
            finished(user, job_queue)
            return
        element = user.next_block[2]
        day_offset = next_day - user.day_
        time_t = calc_block_time(element["time"])
        due = calc_delta_t(time_t, day_offset, user.timezone_)

        debug('QUEUE', 'next block in ' + str(due) + ' seconds. User: ' + str(user.chat_id_), log=True)
        new_job = Job(queue_next, due, repeat=False, context=[user, job_queue])
        user.job_ = new_job
        job_queue.put(new_job)
开发者ID:philippfeldner,项目名称:diary-survey-bot,代码行数:70,代码来源:questions.py

示例10: queue_next

# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import send_message [as 别名]
def queue_next(bot: Bot, job: Job):
    user = job.context[0]  # type: Participant
    job_queue = job.context[1]
    if not user.active_:
        return
    user.block_complete_ = False
    user.job_ = None

    # Stores all unanswered questions to csv
    prev = user.q_set_[user.pointer_]["blocks"][user.block_]["questions"]
    for i in range(user.question_, len(prev)):
        user.increase_question()
        q_prev = prev[i]
        store_answer(user, '', q_prev, job_queue)

    user.set_question(0)
    user.set_pointer(user.next_block[0])
    user.set_block(user.next_block[1])
    element = user.next_block[2]
    user.set_day(user.q_set_[user.pointer_]['day'])

    if ['MANDATORY'] in element['settings']:
        user.auto_queue_ = False
    else:
        user.auto_queue_ = True

    # Check if the user is currently active
    if not user.active_:
        return

    try:
        # Find next question that the user should get.
        while not user.check_requirements(element["questions"][user.question_]):
            store_answer(user, '', element["questions"][user.question_], None)
            user.increase_question()
    except IndexError:
        # User did not fulfill any questions for the day so we reschedule.
        # Set the new day.
        next_day = user.set_next_block()
        if user.next_block is None:
            return finished(user, job_queue)

        element = user.next_block[2]
        day_offset = next_day - user.day_
        time_t = calc_block_time(element["time"])
        due = calc_delta_t(time_t, day_offset, user.timezone_)

        # Add new job and to queue. The function basically calls itself recursively after x seconds.
        debug('QUEUE', 'next block in ' + str(due) + ' seconds. User: ' + str(user.chat_id_), log=True)
        new_job = Job(queue_next, due, repeat=False, context=[user, job_queue])
        user.job_ = new_job
        job_queue.put(new_job)
        return

    # Sending the question
    question = element["questions"][user.question_]
    message = parse_question(user, element["questions"][user.question_])
    q_keyboard = get_keyboard(question["choice"], user)
    try:
        bot.send_message(chat_id=user.chat_id_, text=message, reply_markup=q_keyboard)
        debug(flag="MSG", text=str(user.chat_id_) + ": " + message + "\n")
    except TelegramError as error:
        if error.message == 'Unauthorized':
            user.pause()
    user.set_q_idle(True)

    # Check if there is a reason to queue again.
    if not user.auto_queue_:
        return

    # Calculate seconds until question is due.
    next_day = user.set_next_block()
    if user.next_block is None:
        return finished(user, job_queue)
    element = user.next_block[2]
    day_offset = next_day - user.day_
    time_t = calc_block_time(element["time"])
    due = calc_delta_t(time_t, day_offset, user.timezone_)

    debug('QUEUE', 'next block in ' + str(due) + ' seconds. User: ' + str(user.chat_id_), log=True)
    new_job = Job(queue_next, due, repeat=False, context=[user, job_queue])
    job_queue.put(new_job)
    return
开发者ID:philippfeldner,项目名称:diary-survey-bot,代码行数:85,代码来源:questions.py

示例11: TelegramBot

# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import send_message [as 别名]
class TelegramBot(IntegrationBot):
    """
    Telegram integration. 
    
    Permabots only requires token to set webhook and obtain some bot info.
    
    Follow telegram instructions to create a bot and obtain its token `<https://core.telegram.org/bots#botfather>`_.
    """
    token = models.CharField(_('Token'), max_length=100, db_index=True, unique=True, validators=[validators.validate_token],
                             help_text=_("Token provided by Telegram API https://core.telegram.org/bots"))
    user_api = models.OneToOneField(TelegramUser, verbose_name=_("Telegram Bot User"), related_name='telegram_bot', 
                                    on_delete=models.CASCADE, blank=True, null=True,
                                    help_text=_("Telegram API info. Automatically retrieved from Telegram"))
    
    class Meta:
        verbose_name = _('Telegram Bot')
        verbose_name_plural = _('Telegram Bots')    
    
    def __init__(self, *args, **kwargs):
        super(TelegramBot, self).__init__(*args, **kwargs)
        self._bot = None
        if self.token:
            try:
                self.init_bot()
            except InvalidToken:
                logger.warning("Incorrect token %s" % self.token)
            
    def __str__(self):
        return "%s" % (self.user_api.first_name or self.token if self.user_api else self.token)
    
    def init_bot(self):
        self._bot = TelegramBotAPI(self.token)
    
    @property
    def hook_id(self):
        return str(self.id)
    
    @property
    def hook_url(self):
        return 'permabots:telegrambot'
    
    @property
    def null_url(self):
        return None
    
    @property
    def identity(self):
        return 'telegram'
    
    def set_webhook(self, url):
        self._bot.set_webhook(webhook_url=url)
    
    def message_text(self, message):
        return message.text
    
    def get_chat_state(self, message):
        try:
            return TelegramChatState.objects.select_related('state', 'chat', 'user').get(chat=message.chat, user=message.from_user, state__bot=self.bot)
        except TelegramChatState.DoesNotExist:
            return None
        
    def build_keyboard(self, keyboard):       
        if keyboard:
            keyboard = ast.literal_eval(keyboard)
            keyboard = ReplyKeyboardMarkup(keyboard, resize_keyboard=True)
        else:
            keyboard = ReplyKeyboardHide()
        return keyboard
        
    def create_chat_state(self, message, target_state, context):
        TelegramChatState.objects.create(chat=message.chat,
                                         user=message.from_user,
                                         state=target_state,
                                         ctx=context)
              
    def get_chat_id(self, message):
        return message.chat.id
    
    def send_message(self, chat_id, text, keyboard, reply_message=None, user=None):
        parse_mode = ParseMode.HTML
        disable_web_page_preview = True
        reply_to_message_id = None
        if reply_message:
            reply_to_message_id = reply_message.message_id
        texts = text.strip().split('\\n')
        msgs = []
        for txt in texts:
            for chunk in textwrap.wrap(txt, 4096):
                msgs.append((chunk, None))
        if keyboard:
            msgs[-1] = (msgs[-1][0], keyboard)
        for msg in msgs:
            try:
                logger.debug("Message to send:(chat:%s,text:%s,parse_mode:%s,disable_preview:%s,keyboard:%s, reply_to_message_id:%s" %
                             (chat_id, msg[0], parse_mode, disable_web_page_preview, msg[1], reply_to_message_id))
                self._bot.send_message(chat_id=chat_id, text=msg[0], parse_mode=parse_mode, 
                                       disable_web_page_preview=disable_web_page_preview, reply_markup=msg[1], 
                                       reply_to_message_id=reply_to_message_id)        
                logger.debug("Message sent OK:(chat:%s,text:%s,parse_mode:%s,disable_preview:%s,reply_keyboard:%s, reply_to_message_id:%s" %
                             (chat_id, msg[0], parse_mode, disable_web_page_preview, msg[1], reply_to_message_id))
#.........这里部分代码省略.........
开发者ID:pombredanne,项目名称:permabots,代码行数:103,代码来源:bot.py

示例12: Core

# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import send_message [as 别名]

#.........这里部分代码省略.........
                # Start thread
                bot_thread.start()
                """
                #######################################################################
                # Start the Bot
                self.updater.start_polling(poll_interval=0.05)

        except Exception as e:
            log.error(prelog() + str(e) + '\n' + traceback.format_exc())

    def error(self, bot, update, error):
        log.warn('Update "%s" caused error "%s"' % (update, error))

    def disable(self):
        try:
            log.info(prelog() + 'Disable')
            reactor.callLater(2, self.disconnect_events)
            self.whitelist = []
            self.telegram_poll_stop()
            # self.bot = None
        except Exception as e:
            log.error(prelog() + str(e) + '\n' + traceback.format_exc())

    def update(self):
        pass

    def telegram_send(self, message, to=None, parse_mode=None):
        if 1:  # str(update.message.chat.id) in self.whitelist:
            if self.bot:
                log.debug(prelog() + 'Send message')
                if not to:
                    to = self.config['telegram_user']
                else:
                    log.debug(prelog() + 'send_message, to set')
                if not isinstance(to, (list,)):
                    log.debug(prelog() + 'Convert to to list')
                    to = [to]
                log.debug(prelog() + "[to] " + str(to))
                for usr in to:
                    # Every outgoing message filtered here
                    if str(usr) in self.whitelist or str(usr) in self.notifylist:
                        log.debug(prelog() + "to: " + str(usr))
                        if len(message) > 4096:
                            log.debug(prelog() +
                                      'Message length is {}'.format(str(len(message))))
                            tmp = ''
                            for line in message.split('\n'):
                                tmp += line + '\n'
                                if len(tmp) > 4000:
                                    msg = self.bot.send_message(usr, tmp,
                                                                parse_mode='Markdown')
                                    tmp = ''
                        else:
                            if parse_mode:
                                msg = self.bot.send_message(usr, message,
                                                            parse_mode='Markdown')
                            else:
                                msg = self.bot.send_message(usr, message)
            log.debug(prelog() + 'return')
            return

    def telegram_poll_start(self):
        # Skip this - for testing only
        pass
        """Like non_stop, this will run forever
        this way suspend/sleep won't kill the thread"""
开发者ID:noam09,项目名称:deluge-telegramer,代码行数:70,代码来源:core.py


注:本文中的telegram.Bot.send_message方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。