示例#1
0
    def __init__(self, token, owner_id):
        # create folder for audio storage
        create_directory(self.FILES_DIRECTORY)

        self._mongo = MongoClientWrapper(MONGO)
        super(GatherValidateBot, self).__init__(
            token,
            [
                # Handler for the chat actions
                pave_event_space()(per_chat_id_except([owner_id]),
                                   create_open,
                                   GatherValidateChatHandler,
                                   self._mongo,
                                   timeout=1000000),
                pave_event_space()(per_chat_id_in([owner_id]),
                                   create_open,
                                   OwnerHandler,
                                   self._mongo,
                                   timeout=1000000),

                # download voice file
                (self._is_voice, custom_thread(call(self._download_and_store))
                 ),

                # announce to all users
                (self._is_announce, custom_thread(call(self._announce)))
            ])
示例#2
0
def main(loggingfile, TOKEN):
    logging.basicConfig(filename=loggingfile + '.log',
                        format='%(asctime)-15s %(message)s')
    bot = telepot.DelegatorBot(TOKEN, [
        pave_event_space()(
            per_inline_from_id(), create_open, InlineHandler, timeout=1),
        include_callback_query_chat_id(pave_event_space())(
            per_chat_id(), create_open, MessageHandler, timeout=1)
    ])
    bot.message_loop(run_forever='Listening ...')
示例#3
0
	def __init__(self,token):
		self.adminconfig()
		self.timeconfig()
		x.loadConfig()
		config1.read('telebot.ini')
		idadmin = config1.get('admin','chatid')
		x.camStart()
		super(ChatBox, self).__init__(token, [
			include_callback_query_chat_id(pave_event_space())(per_chat_id_in([int(idadmin)],types='private'), create_open, SmartRoomChat, timeout=90),
			pave_event_space()(per_chat_id_except([int(idadmin)],types='private'), create_open, NonAdmin, timeout=10),
				])
示例#4
0
def run_bot():
    parser = ArgumentParser(description='MTG Card Image Fetch Telegram Bot')
    parser.add_argument('token',
                        type=str,
                        metavar='t',
                        help='The Telegram Bot API Token')
    parser.add_argument('--level',
                        metavar='l',
                        default='info',
                        choices=[l.lower() for l in logging._nameToLevel])
    args = parser.parse_args()

    logging.basicConfig(level=args.level.upper(),
                        format='%(asctime)s | %(levelname)s: %(message)s',
                        datefmt='%m.%d.%Y %H:%M:%S',
                        handlers=[
                            logging.StreamHandler(),
                            logging.FileHandler(
                                'mtgbot_{:%Y_%m_%d_%X}.log'.format(
                                    datetime.now()))
                        ])

    bot = telepot.DelegatorBot(args.token, [
        pave_event_space()(
            per_inline_from_id(), create_open, InlineHandler, timeout=20),
    ])

    bot.message_loop(run_forever='Listening ...')
示例#5
0
def start_bot(config):
    rasa_section = config['rasa']
    telegram_section = config['telegram']

    logger.info('Loading model')

    model = get_model(rasa_section)
    metadata = Metadata.load(model)

    logger.info('Loading interpreter')

    rasa_config = rasa_section['config']

    interpreter = Interpreter.load(metadata, RasaNLUConfig(rasa_config))

    logger.info('Preparing Bot')

    token = telegram_section['token']

    bot = telepot.DelegatorBot(token, [
        pave_event_space()(per_chat_id(),
                           create_open,
                           KiririnHandler,
                           interpreter,
                           config,
                           timeout=20)
    ])

    MessageLoop(bot).run_as_thread()

    logger.info('Listening')

    while 1:
        time.sleep(10)
示例#6
0
def main():
    parser = ArgumentParser()
    parser.add_argument('--token', type=str, required=True)
    parser.add_argument('--smartid-config',
                        type=str,
                        default='bundle_mock_smart_idreader.zip')
    args = parser.parse_args()

    # Creating recognition engine
    smartid_engine = se.RecognitionEngine(args.smartid_config)

    # Creating bot
    bot = telepot.DelegatorBot(args.token, [
        pave_event_space()(per_chat_id(),
                           create_open,
                           SmartIDReaderBot,
                           smartid_engine,
                           timeout=1000000)
    ])

    # Starting bot
    MessageLoop(bot).run_as_thread()
    print('Bot started, listening to messages...')

    while 1:
        time.sleep(10)
示例#7
0
def main():
    TOKEN = os.getenv(TOKEN)
    assert TOKEN, "You should export 'TOKEN' env variable"
    bot = telepot.DelegatorBot(TOKEN, [
        pave_event_space()(per_chat_id(), create_open, Player, timeout=10),
    ])
    bot.message_loop(run_forever='Listening ...')
示例#8
0
def run():
    setting_lst = []
    setting_lst.append(pave_event_space()(per_chat_id(),
                                          create_open,
                                          gnomo,
                                          timeout=1000))
    bot = telepot.DelegatorBot(TOKEN, setting_lst)
    bot.message_loop(run_forever="listening ...")
示例#9
0
    def __init__(self, token):
        super().__init__(token, [
            include_callback_query_chat_id(pave_event_space())(
                per_chat_id(), create_open, TheManager, timeout=10),
        ])

        self.spotify_controller = SpotifyController(self)
        self.game_controller = LyricGameController(self)
示例#10
0
def main():
    setup_bot(PLATFORM)
    bot = DelegatorBot(BOT_TOKEN, [
        pave_event_space()(
            per_application(), create_open, NewsApiTelegramBot, timeout=np.inf)
    ])
    MessageLoop(bot).run_as_thread()

    while 1:
        time.sleep(3600)
def main():
    bot = DelegatorBot(token, [
        pave_event_space()(per_chat_id(types=['group']),
                           create_open,
                           TelegramManager,
                           timeout=300)
    ])
    MessageLoop(bot).run_as_thread()

    while 1:
        time.sleep(10)
示例#12
0
def main():
    bot = telepot.DelegatorBot("API_BOT", [
        pave_event_space()(
            per_chat_id(), create_open, SSHGenerator, timeout=10),
    ])
    MessageLoop(bot).run_as_thread()

    # Keep the program running.
    while 1:
        time.sleep(1)
        pass
def main_loop(app, queue=None):
    """Main loop of the bot.

    :param flask.app.Flask app: Flask app.
    :param queue: Update queue to be used as the source of updates instead of the Telegram API server. Used in tests.
    """
    bot = DelegatorBot(
        TELEGRAM_TOKEN,
        [pave_event_space()(per_chat_id(), create_open, ChoreBot, timeout=TELEGRAM_IDLE_TIMEOUT, flask_app=app)],
    )
    forever = False if queue else "Listening ({})...".format(app.config["ENV"])
    bot.message_loop(source=queue, run_forever=forever)
示例#14
0
def main():
    bot = telepot.DelegatorBot(
        "1301161841:AAFoG-7rf1IeQbG-gpEagw47pbvMxpcz3qI", [
            pave_event_space()(
                per_chat_id(), create_open, SSHGenerator, timeout=10),
        ])
    MessageLoop(bot).run_as_thread()

    # Keep the program running.
    while 1:
        time.sleep(1)
        pass
示例#15
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)
示例#16
0
def main():
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djing.settings")
    django.setup()
    from chatbot.telebot import token, DjingTelebot
    while True:
        try:
            bot = DelegatorBot(token, [
                pave_event_space()(
                    per_chat_id(), create_open, DjingTelebot, timeout=300
                ),
            ])
            bot.message_loop(run_forever='Listening ...')
        except BadHTTPResponse as e:
            print(e)
示例#17
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)
示例#18
0
    def __init__(self, token, members, polls, students):
        self._polls = polls
        self._members = members
        self._students = students

        super(Congress, self).__init__(token, [
            include_callback_query_chat_id(pave_event_space())(
                per_chat_id(types=['private']),
                create_open,
                Member,
                self._polls,
                self._members,
                self._students,
                timeout=20),
        ])
示例#19
0
    def __init__(self, token, owner_id):
        self._owner_id = owner_id
        self._seen = set()
        self._store = UnreadStore()

        super(ChatBox, self).__init__(token, [
            # Here is a delegate to specially handle owner commands.
            pave_event_space()(
                per_chat_id_in([owner_id]), create_open, OwnerHandler, self._store, timeout=20),

            # Only one MessageSaver is ever spawned for entire application.
            (per_application(), create_open(MessageSaver, self._store, exclude=[owner_id])),

            # For senders never seen before, send him a welcome message.
            (self._is_newcomer, custom_thread(call(self._send_welcome))),
        ])
示例#20
0
    def __init__(self, token, owner_id):
        self._owner_id = owner_id
        self._seen = set()
        self._store = UnreadStore()

        super(ChatBox, self).__init__(token, [
            # Here is a delegate to specially handle owner commands.
            pave_event_space()(
                per_chat_id_in([owner_id]), create_open, OwnerHandler, self._store, timeout=20),

            # Only one MessageSaver is ever spawned for entire application.
            (per_application(), create_open(MessageSaver, self._store, exclude=[owner_id])),

            # For senders never seen before, send him a welcome message.
            (self._is_newcomer, custom_thread(call(self._send_welcome))),
        ])
示例#21
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()
示例#22
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'])
示例#23
0
 def __init__(self, config, on_idle_timeout=None):
     self.config = config
     if on_idle_timeout is not None:
         self.on_idle_timeout = on_idle_timeout
     else:
         self.on_idle_timeout = config.ON_IDLE_TIMEOUT
     super(TwitterBotDelegatorBot, self).__init__(
         config.TELEGRAM_BOT_TOKEN,
         [
             # Here is a delegate to specially handle owner commands.
             delegate.pave_event_space()(
                 delegate.per_chat_id_in(config.AUTHORIZED_USERS,
                                         types='private'),
                 delegate.create_open,
                 TwitterBotChatHandler,
                 # Add handler arguments here
                 config=config,
                 timeout=self.on_idle_timeout)
         ])
示例#24
0
    def __init__(self, token):
        self._seen = set()
        self._store = MongoStore()

        super(ChatBox, self).__init__(
            token,
            [
                # Here is a delegate to specially handle owner commands.
                pave_event_space()(per_chat_id_in(self._store.getUsers()),
                                   create_open,
                                   CommandsBrain,
                                   self._store,
                                   timeout=100),

                # Only one MessageSaver is ever spawned for entire application.
                (per_application(),
                 create_open(MessageSaver, self._store, exclude=[])),

                # For senders never seen before, send him a welcome message.
                (self._is_newcomer, print('Welcome mate!')),
            ])
示例#25
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)
示例#26
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)
示例#27
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)
示例#28
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 ...')
示例#29
0
文件: bot.py 项目: erastov/tictactoe
                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)
示例#30
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)
示例#31
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 ...')
示例#32
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)
示例#33
0
文件: bot.py 项目: S-X-ShaX/telebot
		## Journal.
		try:
			print("\033[33m>>>\033[0m %s\n\033[33mBot\033[0m: Closed an delegator with @\033[34m%s\033[0m by calling on_close()."%(self._now, self._username))
		except:
			print("\033[33m>>>\033[0m %s\n\033[33mBot\033[0m: Closed an delegator by calling on_close()."%(self._now))
		print("--------------------------------------------")


### Now it starts run.
print("Getting bot information...")

### Generate a bot object.
bot = telepot.DelegatorBot(
	TOKEN, [
			pave_event_space()(
			per_from_id(),
			create_open, TeleBot, timeout=30
		)
	]
)


### Now it prints your bot information.
try:
	info = bot.getMe()
except KeyboardInterrupt:
	exit()
except:
	conf_rewrite = False
	print("\033[46m\033[31mERROR\033[0m: Your token is invaild.")
	print("Please check what your config file \"%s\" contains."%(config_file))
	print("It should contain your token string in the token line.")
示例#34
0
        result = self._count_votes()
        self._close_ballot()
        self.sender.sendMessage('Time is up:\nYes: %d\nNo: %d\nSilent: %d' % result)

    def on_close(self, ex):
        global votes
        if self._ballot_box is None:
            try:
                del votes[self.id]
            except KeyError:
                pass
        else:
            votes[self.id] = (self._ballot_box, self._keyboard_msg_ident, self._expired_event)

        from pprint import pprint
        pprint(votes)


TOKEN = sys.argv[1]

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

while 1:
    time.sleep(10)
示例#35
0
            self._count += 1
            text = '%d. %s' % (self._count, query_string)

            articles = [InlineQueryResultArticle(
                            id='abc',
                            title=text,
                            input_message_content=InputTextMessageContent(
                                message_text=text
                            )
                       )]

            return articles

        self.answerer.answer(msg, compute)

    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]  # get token from command-line

bot = telepot.DelegatorBot(TOKEN, [
    pave_event_space()(
        per_inline_from_id(), create_open, QueryCounter, timeout=10),
])
MessageLoop(bot).run_as_thread()

while 1:
    time.sleep(10)
示例#36
0
    # 2. Define event-handling function
    def on__alarm(self, event):
        print(event)  # see what the event object actually looks like
        self.sender.sendMessage('Beep beep, time to wake up!')

    def on_chat_message(self, msg):
        try:
            delay = float(msg['text'])

            # 3. Schedule event
            #      The second argument is the event spec: a 2-tuple of (flavor, dict).
            # Put any custom data in the dict. Retrieve them in the event-handling function.
            self.scheduler.event_later(delay, ('_alarm', {'payload': delay}))
            self.sender.sendMessage('Got it. Alarm is set at %.1f seconds from now.' % delay)
        except ValueError:
            self.sender.sendMessage('Not a number. No alarm set.')


TOKEN = sys.argv[1]

bot = telepot.DelegatorBot(TOKEN, [
    pave_event_space()(
        per_chat_id(), create_open, AlarmSetter, timeout=10),
])
MessageLoop(bot).run_as_thread()
print('Listening ...')

while 1:
    time.sleep(10)
示例#37
0
文件: plan.py 项目: sepulchered/plan
BOT_HOOK_URL = os.environ.get('BOT_HOOK_URL', '/bot/hook')
BOT_HOST = os.environ.get('BOT_HOST', '')

# bot related
class Planner(telepot.helper.ChatHandler):
    def __init__(self, *args, **kwargs):
        super(Planner, self).__init__(*args, **kwargs)

    def on_chat_message(self, msg):
        self.sender.sendMessage('gigla')


bot = telepot.DelegatorBot(BOT_API_TOKEN, [
    pot_delegate.pave_event_space()(
        pot_delegate.per_chat_id(),
        pot_delegate.create_open,
        Planner,
        timeout=15
    )
])

webhook = pot_loop.OrderedWebhook(bot)

# server related
app = flask.Flask(__name__)

@app.route('/')
def index():
    return 'planner bot'

@app.route(BOT_HOOK_URL, methods=['GET', 'POST'])
def on_event():
示例#38
0
            self.sender.sendMessage('Give me a number, please.')
            return

        try:
           guess = int(msg['text'])
        except ValueError:
            self.sender.sendMessage('Give me a number, please.')
            return

        # check the guess against the answer ...
        if guess != self._answer:
            # give a descriptive hint
            hint = self._hint(self._answer, guess)
            self.sender.sendMessage(hint)
        else:
            self.sender.sendMessage('Correct!')
            self.close()

    def on__idle(self, event):
        self.sender.sendMessage('Game expired. The answer is %d' % self._answer)
        self.close()


TOKEN = sys.argv[1]

bot = telepot.DelegatorBot(TOKEN, [
    pave_event_space()(
        per_chat_id(), create_open, Player, timeout=10),
])
bot.message_loop(run_forever='Listening ...')
示例#39
0
    def __init__(self, *args, **kwargs):
        super(MessageCounter, self).__init__(*args, **kwargs)
        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, [
    pave_event_space()(
        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)
示例#40
0
文件: quiz.py 项目: nickoala/telepot
                inline_keyboard=[list(map(lambda c: InlineKeyboardButton(text=str(c), callback_data=str(c)), choices))]
            ),
        )
        return answer

    def on_callback_query(self, msg):
        query_id, from_id, query_data = telepot.glance(msg, flavor="callback_query")

        if query_data != "start":
            self._score[self._answer == int(query_data)] += 1

        self._answer = self._show_next_question()

    def on__idle(self, event):
        text = "%d out of %d" % (self._score[True], self._score[True] + self._score[False])
        self.editor.editMessageText(text, reply_markup=None)
        self.close()


TOKEN = sys.argv[1]

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

bot.message_loop(run_forever="Listening ...")
示例#41
0
class InlineHandler(telepot.helper.InlineUserHandler, telepot.helper.AnswererMixin):
    def __init__(self, *args, **kwargs):
        super(InlineHandler, self).__init__(*args, **kwargs)

    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):
        from pprint import pprint
        pprint(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, [
    pave_event_space()(
        per_inline_from_id(), create_open, InlineHandler, timeout=10),
])
bot.message_loop(run_forever='Listening ...')
示例#42
0
import sys
import telepot
from telepot.delegate import pave_event_space, per_chat_id, create_open


class MessageCounter(telepot.helper.ChatHandler):
    def __init__(self, *args, **kwargs):
        super(MessageCounter, self).__init__(*args, **kwargs)
        self._count = 0

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


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

bot = telepot.DelegatorBot(TOKEN, [pave_event_space()(per_chat_id(), create_open, MessageCounter, timeout=10)])
bot.message_loop(run_forever="Listening ...")
示例#43
0
    if content_type == 'text':
        sent = bot.sendInvoice(
                   chat_id, "Nick's Hand Cream", "Keep a man's hand like a woman's",
                   payload='a-string-identifying-related-payment-messages-tuvwxyz',
                   provider_token=PAYMENT_PROVIDER_TOKEN,
                   start_parameter='abc',
                   currency='HKD', prices=[
                       LabeledPrice(label='One Case', amount=987),
                       LabeledPrice(label='Package', amount=12)],
                   need_shipping_address=True, is_flexible=True)  # required for shipping query

        print('Invoice sent:')
        pprint(sent)


TOKEN = sys.argv[1]
PAYMENT_PROVIDER_TOKEN = sys.argv[2]

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

MessageLoop(bot).run_as_thread()

while 1:
    time.sleep(10)
示例#44
0
        if 'cb_message' in self.context and self.context['cb_message'] != self.context.get('last_message'):
            stage.base_message(
                'Finish',
                update_msg=self.context['cb_message'],
                with_keyboard= 'last_message' not in self.context
            )

        if 'last_message' in self.context:
            self.user_config.data['last_message'] = self.context['last_message']
        
        self.user_config.context = dict()
        self.user_config.save()


if __name__ == '__main__':
    conn = get_connect()
    params = list(model.GlobalConfig.objects.timeout(True))

    bot = telepot.DelegatorBot(config.BOT_TOKEN, [
        pave_event_space()(
            [per_chat_id(('private',)), per_callback_query_chat_id(('private',))],
            create_open,
            EatSession,
            include_callback_query=True, timeout=300),
    ])
    
    MessageLoop(bot).run_as_thread()
    print('Listening ...')
    
    while 1:
        time.sleep(10)
示例#45
0
                        to_buy_list.append(msg['text'])
                        self.sender.sendMessage(text=u'仲有冇?如果冇,就用 /done 完結。', reply_markup={'hide_keyboard': True})
                else:
                    self.sender.sendMessage(text=u'我唔明呀。\n' +
                                                 u'你試多次啦。或者用 /help 我就教你用。')

            else:
                self.sender.sendMessage(text=u'你邊位呀?')
        else:
            raise telepot.exception.BadFlavor(msg)

        print(u'to buy list: ' + self.genBuyList())

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

with open(file=file_name, mode='r') as f:
    lines = f.read().splitlines()
f.close()
to_buy_list = lines

# bot = telepot.DelegatorBot(TOKEN, [
#     (per_chat_id(), create_open(AngryJinny, timeout=120)),])
bot = telepot.DelegatorBot(TOKEN, [
    pave_event_space()(
        per_chat_id(), create_open, AngryJinny, timeout=120),
])
# print('Listening ...')
# bot.notifyOnMessage(run_forever=True)
bot.message_loop(run_forever='Listening ...')