Beispiel #1
0
def run2():
    setting_lst = []
    setting_lst.append(pave_event_space()(per_chat_id(),
                                          create_open,
                                          gnomo,
                                          timeout=100000))
    bot = telepot.DelegatorBot(TOKEN, setting_lst)

    # app.run( port=PORT, debug=True)
    bot.setWebhook()
    bot.setWebhook(URL + SECRET)
    bot.message_loop(source=update_queue)
Beispiel #2
0
def main():

    # Get the dispatcher to register handlers
    bot = telepot.DelegatorBot(token, [
        (per_inline_from_id(), create_open(HowDoIBot, timeout=30)),
        (per_chat_id(), create_open(HowDoIBot, timeout=10)),
    ])
    logger.info('Starting bot')
    # bot.message_loop({'inline_query': on_inline_query,
    #                   'chosen_inline_result': on_chosen_inline_result,
    #                   'chat': on_chat_message},
    #                  run_forever='Listening ...')
    bot.message_loop(run_forever='Listening ...')
Beispiel #3
0
def main():
    global config, bot
    with open("./config.yml") as f:
        data = f.read()
        config = yaml.full_load(data)
    if config['proxy'] is not None:
        telepot.api.set_proxy(config['proxy'])
    bot = telepot.DelegatorBot(config['token'], [
        pave_event_space()(
            per_chat_id(), create_open, WinneAVSearcher, timeout=120)
    ])
    MessageLoop(bot).run_as_thread()
    print('Listening ...')
    while 1:
        time.sleep(20)
Beispiel #4
0
def main():  # starts everything
    global bot_g, formatter_g, logger_g
    # prepare log formatter
    f = open(GENERAL_CONFIG_FILE)
    try:
        config = yaml.safe_load(f)
    finally:
        f.close()
    log_format = config['logger']['format']
    formatter_g = logging.Formatter(
        log_format)  # '%(asctime)s %(levelname)s %(message)s' or similar
    # set logger to file from config
    LOGFILE = config['logger']['log_file']
    logger_g = setup_logger(name=__name__,
                            log_file=LOGFILE,
                            level=logging.DEBUG,
                            formatter=formatter_g,
                            printout=True)
    print 'set logfile to {}'.format(LOGFILE)

    # load token from config file and set global bot_g variable
    f = open(SECRET_CONFIG_FILE)  # close file in case of crash
    try:
        secret_config = yaml.safe_load(f)
    finally:
        f.close()
    token = secret_config['mainconfig']['token']
    bot_g = telepot.DelegatorBot(
        token,
        [
            telepot.delegate.pave_event_space()(
                telepot.delegate.per_chat_id(),
                telepot.delegate.create_open,
                ShiverBot,
                timeout=600  # 10 minutes
            ),
        ])

    # initialize own name
    bot_g.name = bot_g.getMe()['username']
    print 'I am {}'.format(bot_g.name)

    # run listener
    telepot.loop.MessageLoop(bot_g).run_as_thread()
    print 'I am listening...'

    while 1:
        time.sleep(10)
Beispiel #5
0
def main():
    global bot, authorized_users, verbose, scheduler, owm, owm_api_key, city_list
    config_filename = 'weatherbot-config.json'
    try:
        with open(config_filename, 'r') as config_file:
            config = json.load(config_file)
    except FileNotFoundError:
        print('Error: config file "{}" not found: {}'.format(config_filename))
        return
    except ValueError as e:
        print('Error: invalid config file "{}": {}'.format(config_filename, e))
        return
    telegram_bot_token = config.get('telegram_bot_token')
    if not telegram_bot_token:
        print('Error: config file doesn’t contain a `telegram_bot_token`')
        return
    authorized_users = config.get('authorized_users')
    if type(authorized_users) is not list or len(authorized_users) == 0:
        print('Error: config file doesn’t contain an `authorized_users` list')
        return
    verbose = config.get('verbose', True)
    owm_api_key = config.get('openweathermap', {}).get('api_key')
    owm = OpenWeatherMap(owm_api_key) if owm_api_key else None

    city_list_filename = config.get('openweathermap', {}).get('city_list')
    city_list = CityList()
    if city_list_filename:
        city_list.read(
            city_list_filename, lambda p: print(
                '\rLoading city list ... {:d}%'.format(p), end='', flush=True))
        print()

    bot = telepot.DelegatorBot(telegram_bot_token, [
        include_callback_query_chat_id(pave_event_space())(per_chat_id_in(
            authorized_users, types='private'),
                                                           create_open,
                                                           ChatUser,
                                                           timeout=3600)
    ])
    scheduler.start()
    try:
        bot.message_loop(run_forever='Bot listening ...')
    except KeyboardInterrupt:
        pass
    if verbose:
        print('Exiting ...')
    scheduler.shutdown()
Beispiel #6
0
    def on_chat_message(self, msg):

        bot = telepot.DelegatorBot(
            '333028480:AAG2EAmXyBfGqV4XYyD7iD7EEZnd6zvil78', [
                pave_event_space()(
                    per_chat_id(), create_open, MessageCounter, timeout=10),
            ])
        bot.message_loop()  # take updates from queue

        print(msg)
        chat_id = msg['chat']['id']

        if 'text' in msg:
            if re.search(r'hello', msg['text'], re.MULTILINE):
                bot.sendMessage(chat_id,
                                'hello word',
                                reply_to_message_id=msg['message_id'])
Beispiel #7
0
def main():
    global BOT_USERNAME

    bot = telepot.DelegatorBot(BOT_TOKEN, [
        pave_event_space()(
            per_chat_id(), create_open, HyvinvointiChat, timeout=BOT_TIMEOUT)
    ])

    BOT_USERNAME = bot.getMe()["username"].lower()

    flush_messages(bot)

    MessageLoop(bot).run_as_thread()
    print('Listening @{} ...'.format(bot.getMe()["username"]))

    while 1:
        _, points_last_updated = dbm.get_team_points()
        t = datetime.datetime.fromtimestamp(time.time())
        t_prev = datetime.datetime.fromtimestamp(points_last_updated)
        #if not is_today(points_last_updated):
        if t.hour != t_prev.hour and (t.hour % UPDATE_POINTS_INTERVAL_H) == 0:
            dbm.update_team_points()
        time.sleep(10)
Beispiel #8
0
def run_bot(token, config):
    files_tree_generators= {}
    for shared_directories in config.values():
        for sd in shared_directories:
            if sd.path not in files_tree_generators:
                files_tree_generators[sd.path] = nav.FilesTreeGenerator(sd.path)

    global global_config
    global_config = config
    global global_files_tree_generators
    global_files_tree_generators = files_tree_generators

    bot = telepot.DelegatorBot(token, [
        include_callback_query_chat_id(
            pave_event_space())(
            per_chat_id(types=['private']), create_open, NavigatorBot, timeout=300),
    ])
    MessageLoop(bot).run_as_thread()
    logging.info("Listening started")
    print('Listening ...')

    while 1:
        time.sleep(10)
Beispiel #9
0
def main():
    if not BOT_TOKEN:
        print(BOT_TOKEN_NOT_FOUND_MESSAGE)
        sys.exit(1)

    try:
        bootstrap_database()

        bot = telepot.DelegatorBot(BOT_TOKEN, [
            include_callback_query_chat_id(pave_event_space())(
                per_chat_id(types=['private']),
                create_open,
                MessageHandler,
                timeout=10),
        ])

        urls = UrlsHistory.select().order_by('-created_at')

        bot.message_loop(run_forever='At your service. '
                         'There are {} urls '
                         'on the history.'.format(urls.count()))
    except KeyboardInterrupt:
        print('Finishing by your request. Bye!\n')
        sys.exit(0)
Beispiel #10
0
        pprint(msg)
        my_chat_id = msg['chat']['id']
        command = msg['text']
        self._count += 1
        self.sender.sendMessage("count: %d chat id: %s command: %s" %
                                (self._count, my_chat_id, command))


#
# register the bot and start it
#

import config
# Il token è contenuto nel file config.py e non è aggiornato su GitHub per evitare utilizzi impropri
TOKEN = config.TOKEN

bot = telepot.DelegatorBot(os.environ['SSH_BOT_KEY'], [
    pave_event_space()(per_chat_id(), create_open, PushButtonBot,
                       timeout=1000),
])

bot.message_loop(run_forever=False, timeout=2)

print
"Message loop started"

button = BotButton('PC17', bot)

while True:
    time.sleep(100000)
Beispiel #11
0
    if now == last_reminder:
        return
    while last_reminder != now:
        send_reminder(bot, '{:02}:{:02}'.format(*last_reminder))
        last_reminder[1] += 1
        if last_reminder[1] >= 60:
            last_reminder[0] += 1
            last_reminder[1] -= 60
            if last_reminder[0] >= 24:
                last_reminder[0] -= 24
    try:
        with open(config.TELEGRAM_STATE, 'w') as f:
            f.write('{:02}:{:02}'.format(*last_reminder))
    except IOError as e:
        logging.warn('Could not write state file: %s', e)


if __name__ == '__main__':
    logging.basicConfig(level=logging.WARNING,
                        format='%(asctime)s %(message)s',
                        datefmt='%H:%M:%S')
    database.connect()
    bot = telepot.DelegatorBot(config.TELEGRAM_TOKEN, [
        pave_event_space()(
            per_chat_id(types=['private']), create_open, Player, timeout=10),
    ])
    MessageLoop(bot).run_as_thread()
    while 1:
        send_reminders(bot)
        time.sleep(10)
Beispiel #12
0
"""

class InlineHandler(telepot.helper.InlineUserHandler):
    def __init__(self, seed_tuple, timeout):
        super(InlineHandler, self).__init__(seed_tuple, timeout)
        self._answerer = telepot.helper.Answerer(self.bot)

    def on_inline_query(self, msg):
        def compute_answer():
            query_id, from_id, query_string = telepot.glance(msg, flavor='inline_query')
            print(self.id, ':', 'Inline Query:', query_id, from_id, query_string)

            articles = [{'type': 'article',
                             'id': 'abc', 'title': query_string, 'message_text': query_string}]

            return articles

        self._answerer.answer(msg, compute_answer)

    def on_chosen_inline_result(self, msg):
        result_id, from_id, query_string = telepot.glance(msg, flavor='chosen_inline_result')
        print(self.id, ':', 'Chosen Inline Result:', result_id, from_id, query_string)


TOKEN = sys.argv[1]

bot = telepot.DelegatorBot(TOKEN, [
    (per_inline_from_id(), create_open(InlineHandler, timeout=10)),
])
bot.message_loop(run_forever=True)
Beispiel #13
0
            return None
        else:
            bot.sendMessage(chat_id, errorMsg)



    def on_callback_query(self, msg): ##query data
        """find out which quiz the person last did. per_chat_id stores the quizzes the person last did"""
        query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
        print('Response:', query_id, from_id, query_data)
        oncallbackobject=updated_gspread() 
        quizno=query_data[:3] ##assign the first 3 characters of query_data which represents the query id that the user did to variable quizno
        if quizno not in self.quizzes_done:
            data=query_data[-3:]
            oncallbackobject.add_count(quizno,data)
            bot.answerCallbackQuery(query_id, text='You chose ' + query_data[-3:].upper() + '!', show_alert=True)
            bot.sendMessage(from_id, "Thank you for your response! \n\nType 'elab <your feedback> 'to provide feedback. It's anonymous! Click /start to answer another query!")
            self.quizzes_done.append(quizno) ## adds this query id to the list of queries that is done by the user
        else:
            bot.sendMessage(from_id, "You have already done this query. Click /start to select another query") # checks if the user did this query before, prompt user to do another query



bot = telepot.DelegatorBot(TOKEN, [
    include_callback_query_chat_id(
        pave_event_space())(
            per_chat_id(types=['private']), create_open, YayOrNay, timeout=999999999999),
])
print('Listening to responses...')

bot.message_loop(run_forever='Listening ...')
                                    "Please type 'help' for options")
            return

        # Make the commands case insensitive
        command = msg['text'].lower()
        if command not in COMMANDS:
            self.sender.sendMessage("I don't understand you. "
                                    "Please type 'help' for options")
            return

        message = COMMANDS[command]()
        self.sender.sendMessage(message)

    def on_idle(self, event):
        self.close()

    def on_close(self, event):
        # Add any required cleanup here
        pass


# Create and start the bot
bot = telepot.DelegatorBot(TOKEN, [
    pave_event_space()(per_chat_id(), create_open, MarketingBot, timeout=10),
])
MessageLoop(bot).run_as_thread()
print('Listening ...')

while 1:
    time.sleep(10)
Beispiel #15
0
def bot_app_start(token):
    bot = telepot.DelegatorBot(token, [
        pave_event_space()(per_chat_id(), create_open, HutPizza, timeout=300),
    ])
    log.info("Bot started..........")
    MessageLoop(bot).run_as_thread()
Beispiel #16
0
                                                  '_': lambda msg: True
                                              }])
        self._count = 0

    def on_message(self, msg):
        self._count += 1
        flavor = telepot.flavor(msg)

        print '%s %d: %d: %s: %s' % (type(self).__name__, self.id, self._count,
                                     flavor, telepot.glance(msg,
                                                            flavor=flavor))


# Do some simple stuff for every message, to be paired with per_message()
def simple_function(seed_tuple):
    bot, msg, id = seed_tuple
    print 'Simply print:', msg


TOKEN = sys.argv[1]

bot = telepot.DelegatorBot(TOKEN, [
    (per_chat_id(), create_open(ChatHandlerSubclass, timeout=10)),
    (per_from_id(), create_open(UserHandlerSubclass, timeout=20)),
    (per_inline_from_id(),
     create_open(UserHandlerSubclassInlineOnly, timeout=10)),
    (per_application(), create_open(OnlyOneInstance)),
    (per_message(), call(simple_function)),
])
bot.message_loop(run_forever=True)
Beispiel #17
0
        if from_id in users:
            del users[from_id]
        bot.sendMessage(from_id,startMsg, reply_markup=startKeyboard)
        #os._exit(1)
        

class MessageCounter(telepot.helper.ChatHandler):
    def __init__(self, *args, **kwargs):
        super(MessageCounter, self).__init__(*args, **kwargs)
        self._count = 0
    
    def open(self, initial_msg, seed):
        return True  # prevent on_message() from being called on the initial message
    
    def on_chat_message(self, msg):
        self._count += 1
        self.sender.sendMessage(self._count)

if __name__ == '__main__':

    srtoken = getToken()
    bot = telepot.DelegatorBot(srtoken, [
        pave_event_space()(
        per_chat_id(), create_open, MessageCounter, timeout=10),
    ])
    
    MessageLoop(bot, {'chat': handle_message,'callback_query': reserve_query}).run_as_thread()
    print('[+] ---------- Start Listening ----------')

    while True:
        time.sleep(10)
Beispiel #18
0
        self.order = {}

    def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)
        if self.indicator == 'add url':

            self.indicator = 'choose_payment'
        elif self.indicator == 'choose_payment':
            self.order['order'] = msg['text']

            self.indicator = 'set_order'
        elif self.indicator == 'set_order':
            self.order['payment'] = msg['text']

            with open('order.json', 'a') as handle:
                json.dump(self.order, handle)
                handle.write("\n")
                handle.close()
            bot.sendMessage(chat_id, 'Order Accepted')


token = '741409888:AAFd63l_boS5xLuWUWx1Ff1ZxlnfUKKkv2w'
#bot = telepot.Bot(token)
bot = telepot.DelegatorBot(token, [
    pave_event_space()(per_chat_id(), create_open, GoldenArches, timeout=10),
])
MessageLoop(bot).run_as_thread()
print('Listening ...')
while 1:
    time.sleep(10)
Beispiel #19
0
            self._buy_or_not = True
            self._buy_info_flag = False
        if query_data == 'buy_book_no':
            keyboard = InlineKeyboardMarkup(
                inline_keyboard=[[
                    InlineKeyboardButton(text='Yes',
                                         callback_data='search_other_book_yes')
                ],
                                 [
                                     InlineKeyboardButton(
                                         text='No',
                                         callback_data='search_other_book_no')
                                 ]])
            bot.sendMessage(from_id,
                            'Do you wanna search for other books',
                            reply_markup=keyboard)


TOKEN = '430811551:AAEUJoN6B8hajtfHi2q9sz8gBYvlh3JjGuo'

bot = telepot.DelegatorBot(TOKEN, [
    include_callback_query_chat_id(pave_event_space())(
        per_chat_id(), create_open, ChatHandler, timeout=1000000000000000000),
])
bot.deleteWebhook()
MessageLoop(bot).run_as_thread()
print('Listening ...')

while 1:
    time.sleep(10)
Beispiel #20
0
    def on_callback_query(self, msg):
        query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')

        if query_data == 'yes':
            # hide inline keyboard
            self._editor.editMessageReplyMarkup(reply_markup=None)
            self.sender.sendMessage('Thank you!')
            self.close()
        else:
            self.bot.answerCallbackQuery(query_id, text='Ok. But I am going to keep asking.')

            # hide inline keyboard
            self._editor.editMessageReplyMarkup(reply_markup=None)

            self._count += 1
            sent = self.sender.sendMessage('%d. Would you marry me?' % self._count, reply_markup=self._keyboard)
            self._editor = telepot.helper.Editor(self.bot, sent)


TOKEN = sys.argv[1]

bot = telepot.DelegatorBot(TOKEN, [
    (per_chat_id(types=['private']), create_open(Lover, timeout=10)),
])
bot.message_loop()
print('Listening ...')

while 1:
    time.sleep(10)
Beispiel #21
0
            return None
        cmd_start = def_command['offset']
        cmd_length = def_command['length']
        txt = msg["text"]
        cmd_text = txt[cmd_start:cmd_start + cmd_length]
        cmd = cmd_text.split('@')[0]
        return cmd


PROD_TOKEN = "311427299:AAH383yX1vqVsGR_59qJp3bdkTFbrr-UN38"
DEV_TOKEN = "409284378:AAGOvaA_SRaKrbb-gL6z-yWnK3260MTEGyc"
TOKEN = DEV_TOKEN  # by default we have dev token

if len(sys.argv) > 1 and sys.argv[1] == "prod":
    TOKEN = PROD_TOKEN
    print("Bot will start in production mode")
else:
    print("Bot will start in development mode")

bot = telepot.DelegatorBot(TOKEN, [
    pave_event_space()(
        per_chat_id(types=['private', 'channel', 'group', 'supergroup']),
        create_open,
        VoteCounter,
        timeout=10),
])
MessageLoop(bot).run_as_thread()
print('Listening ...')

while 1:
    time.sleep(10)
Beispiel #22
0
                    x.append(datetime.datetime.fromtimestamp(row[0]))
                    y.append(row[1])
            except sqlite3.DatabaseError as err:
                self.bot.sendMessage(admin, "error with database" + str(err))
            else:
                path = self.SaveGraphic(x, y)
                self.sender.sendPhoto(open(path, 'rb'))

    def on__idle(self, event):
        self.markup = ReplyKeyboardRemove()
        self.sender.sendMessage("Good bye", reply_markup=self.markup)


if __name__ == "__main__":
    bot = telepot.DelegatorBot(TOKEN, [
        pave_event_space()(per_chat_id(), create_open, Weather_bot,
                           timeout=90),
    ])
    MessageLoop(bot).run_as_thread()
    print('Listening ...')

    while 1:
        time.sleep(20)
        #file = open('err.log', 'r')
        #data = file.read()
        #if data:
        #bot.sendMessage(admin, data)
        #file.close()
        #file = open('err.log', 'w')
        #file.close()
Beispiel #23
0
                    self.sender.sendMessage(text="لطفا بعد از فرستادن پیام های خود گزینه ارسال را فشار دهید", reply_markup=contact_us_keyboard)
                self.question += msg["text"] + "\n"
                print(self.question)
            elif self.situation // 10 == 16:
                self.presentation_rate = int(msg["text"])
            elif self.situation // 100 == 16:
                self.context_rate = int(msg["text"])
            else:
                pass  # invalid msg

            # TODO handle: not sending responses to messages sent when bot was down ...


# bot = telepot.Bot(TOKEN)
# print(bot.getMe())

bot = telepot.DelegatorBot('797548891:AAHTRcDFwAVb1V7ru2XhszTLZKq9TF8GzJs', [
    pave_event_space()(
        per_chat_id(), create_open, StateHandler, timeout=2 * 24 * 60 * 60),  # timeout = 2 days?
])
start_time_ms = datetime.datetime

MessageLoop(bot).run_forever()

# OR THIS METHOD:

# MessageLoop(bot).run_as_thread()
# while 1:
#     time.sleep(5)
# print('Listening ...')
Beispiel #24
0
            self.id, ':', flavor, '+1', ':', ', '.join([
                str(self._counts[f])
                for f in ['chat', 'inline_query', 'chosen_inline_result']
            ]))

        # Have to answer inline query to receive chosen result
        if flavor == 'inline_query':

            def compute_answer():
                query_id, from_id, query_string = telepot.glance(msg,
                                                                 flavor=flavor)

                articles = [{
                    'type': 'article',
                    'id': 'abc',
                    'title': query_string,
                    'message_text': query_string
                }]

                return articles

            self._answerer.answer(msg, compute_answer)


TOKEN = sys.argv[1]

bot = telepot.DelegatorBot(TOKEN, [
    (per_from_id(), create_open(UserTracker, timeout=20)),
])
bot.message_loop(run_forever=True)
Beispiel #25
0
                self._show_next_state('Я хожу:')
                if not (self._stop or self._winner):
                    self._bot_answer()
                    self._show_next_state('Ты ходишь:')
            else:
                self._counter += 1
                self._show_next_state('Ты слепой? ({}):'.format(self._counter))

    def on__idle(self, event):
        self.editor.editMessageText('Слишком долго думаешь :(\nЯ пошёл 👋',
                                    reply_markup=None)
        time.sleep(5)
        self.editor.deleteMessage()
        self.close()


if __name__ == "__main__":
    TOKEN = '705103229:AAF20n1fAtMQn-1Askb9BKwdKEGyylBG51U'

    bot = telepot.DelegatorBot(TOKEN, [
        pave_event_space()(per_chat_id(), create_open, GameStarter, timeout=3),
        pave_event_space()(
            per_callback_query_origin(), create_open, Gamer, timeout=10),
    ])

    MessageLoop(bot).run_as_thread()
    print('Listening ...')

    while 1:
        time.sleep(10)
Beispiel #26
0
                self.temp_bot = Shop()
            else:
                text = "Sorry, I did't understand :(\nPlease check /help"

            if text != '':
                bot.sendMessage(chat_id=chat_id,
                                text=text,
                                reply_markup=ReplyKeyboardHide())

    def get_shops_keyboard(self):
        keyboard = []

        for shop in self.list_shops:
            keyboard.append([KeyboardButton(text=shop.shopify_hostname)])

        return ReplyKeyboardMarkup(keyboard=keyboard, one_time_keyboard=True)


TOKEN = sys.argv[1]

bot = telepot.DelegatorBot(TOKEN, [
    pave_event_space()(
        per_chat_id(), create_open, CreateShopBot, timeout=sys.maxint),
])

bot.message_loop()

print 'Listening...'
while True:
    time.sleep(10)
Beispiel #27
0
            if content_type == 'new_chat_member':
                new_user_hello(msg)
            if content_type != 'text':
                print('Not a text message.')
                return
            if msg['text'] == '/boobs':
                print('boobs')
                sender_photo(chat_id, instagramm.Inst('boobs'))
                return
            if re.findall('/#.*', msg['text']):
                diez = msg['text'][3:]
                print(diez)
                sender_photo(chat_id, instagramm.Inst(diez))
            # else:
            #     sender_photo(chat_id, 'https://files5.adme.ru/files/comment/part_2036/20357060-1414483493.png')
        except Exception as e:
            sender_photo(
                chat_id,
                'https://files5.adme.ru/files/comment/part_2036/20357060-1414483493.png'
            )


#TOKEN = '307520552:AAHVG_Yi7nshJHUDYOIn-4G6UXEfTY7egGU'
TOKEN = '294022389:AAHVf5mAejze3naL9Q-BAXKEFHlR7Tdk7E4'

bot = telepot.DelegatorBot(TOKEN, [
    include_callback_query_chat_id(pave_event_space())(
        per_chat_id(types=['group']), create_open, VoteCounter, timeout=10),
])
bot.message_loop(run_forever='Listening ...')
Beispiel #28
0
    def __init__(self, seed_tuple, **kwargs):
        super(Session, self).__init__(seed_tuple, **kwargs)
        self.to_delete = []

    def on__idle(self, event):
        for msg in self.to_delete:
            self.bot.deleteMessage(telepot.message_identifier(msg))
        self.close()

    def on_chat_message(self, msg):
        pprint(msg)
        content_type, chat_type, chat_id = telepot.glance(msg)

        if content_type == 'game':
            self.to_delete.append(msg)


if __name__ == "__main__":

    TOKEN = sys.argv[1]  # get token from command-line

    bot = telepot.DelegatorBot(TOKEN, [
        pave_event_space()(per_chat_id(), create_open, Session, timeout=30),
    ])

    MessageLoop(bot).run_as_thread()

    while 1:
        time.sleep(10)
Beispiel #29
0
        super(MessageCounter, self).__init__(seed_tuple, timeout)
        self._count = 0

    def on_chat_message(self, msg):
        self._count += 1
        self.sender.sendMessage(self._count)


TOKEN = sys.argv[1]
PORT = int(sys.argv[2])
URL = sys.argv[3]

app = Flask(__name__)
update_queue = Queue()  # channel between `app` and `bot`

bot = telepot.DelegatorBot(TOKEN, [
    (per_chat_id(), create_open(MessageCounter, timeout=10)),
])
bot.message_loop(source=update_queue)  # take updates from queue


@app.route('/abc', methods=['GET', 'POST'])
def pass_update():
    update_queue.put(request.data)  # pass update to bot
    return 'OK'


if __name__ == '__main__':
    bot.setWebhook(URL)
    app.run(port=PORT, debug=True)
                        need_phone_number=True,
                        reply_markup=kb.custom_inline(price))
                    print(sent)
                    bot.sendMessage(chat_id,
                                    parse_mode='HTML',
                                    text='<b>Add to cart instead?</b>\n'
                                    'Click: /add_{}'.format(name_to_compare))
                    break

            else:
                bot.sendMessage(chat_id,
                                reply_markup=kb.default_keyboard,
                                text='Sorry, there seems to be an error!\n'
                                'Try out some of the actions below?')


bot = telepot.DelegatorBot(
    Token.TOKEN, [(per_message(flavors=['chat']), call(send_invoice)),
                  pave_event_space()(
                      per_invoice_payload(),
                      create_open,
                      OrderProcessor,
                      timeout=30,
                  )])

print('Listening...')
MessageLoop(bot).run_as_thread()

while 1:
    time.sleep(10)