Example #1
0
def delegator_beard_gen(beards):
    for beard in beards:
        if hasattr(beard, "on_callback_query"):
            yield include_callback_query_chat_id(pave_event_space())(
                per_chat_id(), create_open, beard, timeout=beard._timeout)
        else:
            yield pave_event_space()(per_chat_id(),
                                     create_open,
                                     beard,
                                     timeout=beard._timeout)
Example #2
0
 def start(self, token):
     self.bot = telepot.aio.DelegatorBot(token, [
         include_callback_query_chat_id(
             pave_event_space())(
             per_chat_id(), create_open, ShoppingUser, timeout=10),
         ])
     
     self.loop.create_task(MessageLoop(self.bot).run_forever())
     self.loop.run_forever()
Example #3
0
def main():
    bot = telepot.aio.DelegatorBot(TELEGRAM_TOKEN, [
        pave_event_space()(
            per_chat_id(), create_open, MessageCounter, timeout=10),
    ])

    loop = asyncio.get_event_loop()
    loop.create_task(MessageLoop(bot).run_forever())
    loop.run_forever()
Example #4
0
def main(token):
    bot = telepot.aio.DelegatorBot(token, [
        include_callback_query_chat_id(pave_event_space())(
            per_chat_id(types=['private']),
            create_open,
            LentaReader,
            timeout=10),
    ])

    loop = asyncio.get_event_loop()
    loop.create_task(MessageLoop(bot).run_forever())
    print('Listening ...')

    loop.run_forever()
Example #5
0
def main():
    instagram_bot = InstagramAPI(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD)
    instagram_bot.login()

    bot = telepot.aio.DelegatorBot(config('TOKEN'), [
        include_callback_query_chat_id(pave_event_space())(
            per_chat_id(types=['private']), create_open, GeneratePostChatHandler, timeout=10),
    ])

    loop = asyncio.get_event_loop()
    loop.create_task(MessageLoop(bot).run_forever())
    print('Listening ...')

    loop.run_forever()
Example #6
0
    def run(cls):

        token = os.environ['token']
        # token = botconfig.token()

        bot = telepot.aio.DelegatorBot(token, [
            pave_event_space()(
                per_chat_id(), create_open, cls, timeout=cls.timeout),
        ])

        loop = asyncio.get_event_loop()
        loop.create_task(MessageLoop(bot).run_forever())
        print('Listening ...')

        loop.run_forever()
Example #7
0
    def __init__(self, token, reply_threshold=60, botan_key=None):
        super(TeleApp, self).__init__(token, [
            pave_event_space()(
                per_chat_id(), create_open, TeleChat, timeout=10),
            pave_event_space()(
                per_inline_from_id(), create_open, TeleInline, timeout=10)
        ])

        self.reply_threshold = reply_threshold

        botan.set_key(botan_key)

        self._loop = asyncio.get_event_loop()

        self.username = self._loop.run_until_complete(self.getMe())['username']
Example #8
0
def main(args=None):
    """The main routine"""
    if args is None:
        args = sys.argv[1:]

    bot = telepot.aio.DelegatorBot(TOKEN, [
        include_callback_query_chat_id(pave_event_space())(
            per_chat_id(types=["group"]),
            create_open,
            DudoHandler,
            timeout=300),
    ])

    loop = asyncio.get_event_loop()
    loop.create_task(MessageLoop(bot).run_forever())
    loop.run_forever()
Example #9
0
def main():

    # ТУТ БУДЕТ НАШ КОД РАБОТЫ С БАЗОЙ ДАННЫХ
    # КОД ДАЛЬНЕЙШИХ ПРИМЕРОВ ВСТАВЛЯТЬ В ЭТО МЕСТО

    # Не забываем закрыть соединение с базой данных

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

    bot = telepot.aio.DelegatorBot(TOKEN, [
        pave_event_space()(
            per_chat_id(), create_open, AttendanceStarter, timeout=3),
        pave_event_space()(
            per_callback_query_origin(), create_open, Attendance, timeout=60),
    ])

    loop = asyncio.get_event_loop()

    loop.create_task(MessageLoop(bot).run_forever())
    print('Listening ...')

    loop.run_forever()
Example #10
0
"""
$ python3.5 countera.py <token>

Counts number of messages a user has sent. Starts over if silent for 10 seconds.
Illustrates the basic usage of `DelegateBot` and `ChatHandler`.
"""

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

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


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

bot = telepot.aio.DelegatorBot(TOKEN, [
    pave_event_space()(
        per_chat_id(), create_open, MessageCounter, timeout=10),
])

loop = asyncio.get_event_loop()
loop.create_task(bot.message_loop())
print('Listening ...')

loop.run_forever()
Example #11
0
# db = shelve.open("session.db", "c", writeback=True)
atexit.register(lambda: k.saveBrain('brain.sav'))
k = Kernel()  # sessionStore=db)
k.learn("startup.xml")
k.respond("load aiml b")


class MessageKiller(telepot.aio.helper.ChatHandler):
    def __init__(self, *args, **kwargs):
        super(MessageKiller, self).__init__(*args, **kwargs)

    async def on_chat_message(self, msg):
        print("Message text ", msg["text"])
        res = k.respond(msg["text"]).replace("  ", " ").replace("  ", " ")
        print("Response ", res)
        await self.sender.sendMessage(res)


TOKEN = "here_goes_bot_token"

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

loop = asyncio.get_event_loop()
loop.create_task(MessageLoop(bot).run_forever())
print('Listening ...')

loop.run_forever()
Example #12
0
        if query_data != 'start':
            self._score[self._answer == int(query_data)] += 1

        self._answer = await self._show_next_question()

    async def on__idle(self, event):
        text = '%d out of %d' % (self._score[True], self._score[True]+self._score[False])
        await self.editor.editMessageText(
            text + '\n\nThis message will disappear in 5 seconds to test deleteMessage',
            reply_markup=None)

        await asyncio.sleep(5)
        await self.editor.deleteMessage()
        self.close()


TOKEN = sys.argv[1]

bot = telepot.aio.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),
])

loop = asyncio.get_event_loop()
loop.create_task(MessageLoop(bot).run_forever())
print('Listening ...')

loop.run_forever()
Example #13
0
    async def on__idle(self, event):
        self.close()


dotenv_path = join(dirname(__file__), '.env')
if (load_dotenv(dotenv_path)):
    TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
    SPEECH_KIT_API_KEY = os.environ.get("SPEECH_KIT_API_KEY")
    DEBUG = os.environ.get("DEBUG")
else:
    TOKEN = sys.argv[1]  # get token from command-line

if ((SPEECH_KIT_API_KEY != '') and (SPEECH_KIT_API_KEY)):
    bot = telepot.aio.DelegatorBot(TOKEN, [
        include_callback_query_chat_id(pave_event_space())(
            per_chat_id(types=['private']),
            create_open,
            Speech2TextBot,
            SPEECH_KIT_API_KEY,
            timeout=40),
    ])

    loop = asyncio.get_event_loop()
    loop.create_task(bot.message_loop())
    print('Listening ...')

    loop.run_forever()
else:

    print('Please regester your Yandex Speech Kit API Key at \
https://developer.tech.yandex.ru and paste it into SPEECH_KIT_API')
Example #14
0
                    if not self.prolog.selectable_input_options("sauces"):
                        await self.__updateCounter()

                elif user_input in self.prolog.all_options("topups"):
                    self.prolog.add_topup(user_input)

                    if not self.prolog.selectable_input_options("topups"):
                        await self.__updateCounter()

                elif user_input in self.prolog.all_options("sides"):
                    self.prolog.add_side(user_input)

                    if not self.prolog.selectable_input_options("sides"):
                        await self.__updateCounter()

                await self.__ask(id, bot, self.question_lists[self.counter])

            else:
                self.prolog.add_drink(user_input)
                await self.__ask(id, bot, None)


bot = telepot.aio.DelegatorBot(TOKEN, [
    pave_event_space()(per_chat_id(), create_open, TelegramBot, timeout=500),
])

loop = asyncio.get_event_loop()
loop.create_task(MessageLoop(bot).run_forever())
print('Listening ...')

loop.run_forever()
Example #15
0
        query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')

        if from_id in self._votes:
            await self.bot.answerCallbackQuery(query_id, text='You have already voted %s' % self._votes[from_id])
        else:
            await self.bot.answerCallbackQuery(query_id, text='Ok')
            self._votes[from_id] = query_data

        if len(self._votes) >= self._members_count:
            await self._editor.editMessageReplyMarkup(reply_markup=None)
            await self.sender.sendMessage('Everyone has voted. Thank you.')
            await self.sender.sendMessage('Yes: %d\nNo: %d\nSilent: %d' % self._count_votes())

    async def on_timeout(self, exception):
        await self._editor.editMessageReplyMarkup(reply_markup=None)
        await self.sender.sendMessage('Time is up.')
        await self.sender.sendMessage('Yes: %d\nNo: %d\nSilent: %d' % self._count_votes())


TOKEN = sys.argv[1]

bot = telepot.aio.DelegatorBot(TOKEN, [
    (per_chat_id(types=['group']), create_open(VoteCounter, timeout=20)),
])
loop = asyncio.get_event_loop()

loop.create_task(bot.message_loop())
print('Listening ...')

loop.run_forever()
Example #16
0
class MessageCounter(telepot.aio.helper.ChatHandler):
    def __init__(self, *args, **kwargs):
        super(MessageCounter, self).__init__(*args, **kwargs)
        self._count = 0

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


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

bot = telepot.aio.DelegatorBot(TOKEN, [pave_event_space()(per_chat_id(), create_open, MessageCounter, timeout=10)])
update_queue = asyncio.Queue()  # channel between web app and bot


async def webhook(request):
    data = await request.text()
    await update_queue.put(data)  # pass update to bot
    return web.Response(body="OK".encode("utf-8"))


async def init(loop):
    app = web.Application(loop=loop)
    app.router.add_route("GET", "/abc", webhook)
    app.router.add_route("POST", "/abc", webhook)

    srv = await loop.create_server(app.make_handler(), "0.0.0.0", PORT)
                        question = intro[0]['X'] + self.symptom + '?'
                        kb = ReplyKeyboardMarkup(keyboard=[['Yes', 'No']])
                        await bot.sendMessage(id,
                                              gesture + question,
                                              reply_markup=kb)
                self.previous_msg = 'Yes'

            elif (msg['text'] == 'Diagnose'):
                diagnose = list(self.prolog.query('diagnose(X)', maxresult=1))
                self.diagnose = diagnose[0]['X']
                if (self.diagnose == 'no_illness'):
                    outcome = 'You are perfectly healthy! Do continue to exercise and keep fit!'
                else:
                    outcome = 'Based on the symptom(s), you are likely to have {}. Please visit the nearby clinic to get help.'.format(
                        self.diagnose)
                await bot.sendMessage(id, outcome)
                exit()


TOKEN = "1150310497:AAEYmBDdkP21yfCmQR6xd4E2VSPR5p0UNnY"

bot = telepot.aio.DelegatorBot(TOKEN, [
    pave_event_space()(
        per_chat_id(), create_open, PrologInteractor, timeout=500),
])

loop = asyncio.get_event_loop()
loop.create_task(MessageLoop(bot).run_forever())
print('Listening ...')

loop.run_forever()
Example #18
0
# creating the bot

TOKEN = '244035013:AAHXbdprTeisw3hAUWX7VJehWkThR3WwIzk' # bot's own token

# DelegatorBot is a factory
#
# it constructs a new bot,
# if the bot with the same seed(identifier, per_char_id()) doesn't exist
# and seed is hashable
#
# it helps to avoid blocking while listening to the different chats
#
# if no message is captured after TIME seconds,
# delegate is destroyed
#
# more in the documentation:
# https://github.com/nickoala/telepot/blob/master/REFERENCE.md#telepot-DelegatorBot

TIME = 10

bot = telepot.aio.DelegatorBot(TOKEN, [
    (per_chat_id(),
     create_open(MessageHandler, timeout=TIME)),
])

loop = asyncio.get_event_loop()
loop.create_task(bot.message_loop())
print('Listening...')

loop.run_forever()
Example #19
0
            await self.sender.sendMessage('Thank you!')
            self.close()
        else:
            await self.bot.answerCallbackQuery(query_id, text='Ok. But I am going to keep asking.')
            await self._cancel_last()
            await self._propose()

    async def on__idle(self, event):
        await self.sender.sendMessage('I know you may need a little time. I will always be here for you.')
        self.close()

    def on_close(self, ex):
        # Save to database
        global propose_records
        propose_records[self.id] = (self._count, self._edit_msg_ident)


TOKEN = sys.argv[1]

bot = telepot.aio.DelegatorBot(TOKEN, [
    include_callback_query_chat_id(
        pave_event_space())(
            per_chat_id(types=['private']), create_open, Lover, timeout=10),
])

loop = asyncio.get_event_loop()
loop.create_task(MessageLoop(bot).run_forever())
print('Listening ...')

loop.run_forever()
Example #20
0
    print('data path: ' + data_path)

    formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s')

    stream_logger = logging.StreamHandler()
    stream_logger.setFormatter(formatter)
    stream_logger.setLevel(logging.DEBUG)

    logging.basicConfig(level=logging.DEBUG, handlers=[stream_logger])

    loop = asyncio.get_event_loop()
    registry = session.SessionRegistry()
    bot = telepot.aio.DelegatorBot(
        token,
        [pave_event_space()(
            per_chat_id(), create_open, session.Session, data_path, loop,
            registry, timeout=20 * 60)],
        loop
    )
    loop.create_task(bot.message_loop())

    def sigint_handler():
        logging.info('SIGINT')
        try:
            registry.close_all()
        except Exception as e:
            logging.error(e)
        finally:
            loop.stop()

    loop.add_signal_handler(signal.SIGINT, sigint_handler)
Example #21
0
                self.prolog = Prolog()
                self.prolog.consult('Askid.pl')
                self.unused_activities = list(self.activities.keys())
                self.question = random.choice(list(self.activities.keys()))
                self.activity = self.question
                self.prolog.assertz('curr({})'.format(self.question))
            else:
                self.question = random.choice(self.unused_activities)
                self.activity = self.question
                self.prolog.assertz('curr({})'.format(self.question))
            self.prolog.query("assert(asked('{}'))".format(
                self.activities[self.question]))
            kb = ReplyKeyboardMarkup(keyboard=[['YES', 'NO']])
            # await self.sender.sendMessage(self.activities[self.question], reply_markup = kb)
            await bot.sendMessage(id, self.activities[self.question], reply_markup=kb)


# get token from command-line
TOKEN = <YOUR TOKEN>

bot = telepot.aio.DelegatorBot(TOKEN, [
    pave_event_space()(
        per_chat_id(), create_open, PrologReplier, timeout=500),
])

loop = asyncio.get_event_loop()
loop.create_task(MessageLoop(bot).run_forever())
print('Listening ...')

loop.run_forever()
Example #22
0
    async def on_callback_query(self, msg):
        query_id, from_id, query_data = glance(msg, flavor='callback_query')
        print(msg)

        letter = {
            'name': msg['from']['first_name'],
            'chid': msg['message']['chat']['id'],
            'type': '',
            'orgn': msg['message']['text']
        }

        q = query_data.split('♡')
        print(q)


me = key_.adds('me')
mew = key_.adds('mew')

bot = telepot.aio.DelegatorBot(key_.kids('beta'), [
    pave_event_space()(per_chat_id(), create_open, Emperor, timeout=3),
    pave_event_space()(
        per_callback_query_origin(), create_open, Slave, timeout=300),
])

sys.stdout = Unbuffered(sys.stdout)
loop = asyncio.get_event_loop()
loop.create_task(MessageLoop(bot).run_forever())
print('<--- --- Listening ... --- --->')
loop.run_forever()
Example #23
0
        self.save_json(self.quests, 'data/quests.json')

        # save current available raids
        self.save_json(self.curr_raids, 'data/raids.json')

    def save_json(self, obj, filename):
        with open(filename, 'w') as f:
            json.dump(obj, f)

    def convert_to_seconds(self, hours, minutes):
        return int((hours * 3600) + (minutes * 60))

config = json.loads(open('config.json').read())

language = gettext.translation('thepokegobot',
                               localedir='locale',
                               languages=[config['language']])
language.install()

bot = telepot.aio.DelegatorBot(config['token'], [
    include_callback_query_chat_id(pave_event_space())(
        per_chat_id(), create_open, ThePokeGOBot, timeout=600)
])

loop = asyncio.get_event_loop()
loop.create_task(MessageLoop(bot).run_forever())

print(_("Meowth! That's right!"))

loop.run_forever()
Example #24
0
        except ValueError:
            await 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)
            await self.sender.sendMessage(hint)
        else:
            await self.sender.sendMessage('Correct!')
            self.close()

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


TOKEN = sys.argv[1]

bot = telepot.aio.DelegatorBot(TOKEN, [
    pave_event_space()(
        per_chat_id(), create_open, Player, timeout=10),
])

loop = asyncio.get_event_loop()
loop.create_task(MessageLoop(bot).run_forever())
print('Listening ...')

loop.run_forever()
Example #25
0
    async def on_chat_message(self, msg):
        command = msg['text']
        if command == "todas":
            self._count += 1
            todas = futbol.getListOfLeagues()
            await self.sender.sendMessage(todas)
        elif command == "Argentina" or command == "Chile" or command == "Uruguay" or command == "Chile" or command == "Venezuela":
            ligas = futbol.getLeaguesInfo(command)
            await self.sender.sendMessage(ligas)
        elif command == "33424" or command == "37746" or command == "36658" or command == "37744" or command == "33440":
            liga = futbol.getInfoLeague(command)
            await self.sender.sendMessage(liga)
        else:
            await self.sender.sendMessage(
                " Pone Argentina o Uruguay o Venezuela o Chile, luego el codigo de cada liga, o sino tipea todas"
            )


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

bot = telepot.aio.DelegatorBot(TOKEN, [
    pave_event_space()(per_chat_id(), create_open, MessageCounter, timeout=10),
])

loop = asyncio.get_event_loop()
loop.create_task(bot.message_loop())
print('Listening ...')

loop.run_forever()
Example #26
0
def _make_per_chat_handler(handler, **kwargs):
    return pave_event_space()(per_chat_id(), create_open, handler, **kwargs)
Example #27
0
        packname = msg['text']
        try:
            await self.sender.sendChatAction('typing')
            await bot.addStickerToSet(self.from_id, packname,
                                      'BQADBAADiQIAAlrMkFAokegTxHmJZAI',
                                      self.stickeremoji)
            await asyncio.sleep(10.0)
            setobj = await bot.getStickerSet(packname)
            testid = setobj['stickers'][-1]['file_id']
            await bot.deleteStickerFromSet(testid)
            self.packname = packname
            self.packtitle = False
            self.packmade = True
            self.editing = True
            await self.sender.sendMessage(self.donemsg)
        except telepot.exception.TelegramError as e:
            await self.sender.sendMessage(
                'Sorry you dont appear to be the owner of this pack or it doesnt exist.'
            )
            print(e)


bot = telepot.aio.DelegatorBot(key['telegram'], [
    pave_event_space()(per_chat_id(), create_open, Stickers,
                       timeout=70 * 1300),
])
loop = asyncio.get_event_loop()
loop.create_task(MessageLoop(bot).run_forever())
print('Started...')
loop.run_forever()
Example #28
0
                                          parse_mode="Markdown")
            self.waiting_reponse = False

        #if detect any command from other bot answer with a custom message and return a photo
        elif any(word in msg['text']
                 for word in self.antibot_keywords) and self.warmode:
            await self.sender.sendMessage(self.cfg['messages']['antibot'])
            await self.sender.sendPhoto(self.request_image())


#This should be improved TODO
with open(sys.argv[1] + "/config.yaml", 'r') as yamlfile:
    cfg = yaml.safe_load(yamlfile)

TOKEN = cfg['bot']['token']  #read the telegram bot token from the config file

# create a handler for each telegram chat with a lifespan of "timeout"
# if timeout is reached without any new messages it will be destroyed
bot = telepot.aio.DelegatorBot(TOKEN, [
    pave_event_space()(per_chat_id(),
                       create_open,
                       OfftopicBotHandler,
                       timeout=cfg['bot']['timeout']),
])

loop = asyncio.get_event_loop()
loop.create_task(MessageLoop(bot).run_forever())
print('Listening ...')

loop.run_forever()
Example #29
0
    # 2. Define event-handling function
    async def on__alarm(self, event):
        print(event)  # see what the event object actually looks like
        await self.sender.sendMessage('Beep beep, time to wake up!')

    async 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}))
            await self.sender.sendMessage('Got it. Alarm is set at %.1f seconds from now.' % delay)
        except ValueError:
            await self.sender.sendMessage('Not a number. No alarm set.')


TOKEN = sys.argv[1]

bot = telepot.aio.DelegatorBot(TOKEN, [
    pave_event_space()(
        per_chat_id(), create_open, AlarmSetter, timeout=10),
])

loop = asyncio.get_event_loop()
loop.create_task(MessageLoop(bot).run_forever())
print('Listening ...')

loop.run_forever()
Example #30
0
        await 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, self._member_count)

        from pprint import pprint
        print('%d closing ...' % self.id)
        pprint(votes)


TOKEN = sys.argv[1]

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

loop = asyncio.get_event_loop()
loop.create_task(bot.message_loop())
print('Listening ...')

loop.run_forever()
Example #31
0
            self._group = query_data
            await self._show_days(config.days)

    async def on__idle(self, event):
        await asyncio.sleep(5)
        await self.editor.deleteMessage()

        self.close()


def chunks(lst, chunk_count):
    chunk_size = len(lst) // chunk_count
    return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)]


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

bot = telepot.aio.DelegatorBot(TOKEN, [
    pave_event_space()(per_chat_id(), create_open, ScheluderStarter,
                       timeout=3),
    pave_event_space()(
        per_callback_query_origin(), create_open, Scheluder, timeout=60),
])

loop = asyncio.get_event_loop()

loop.create_task(MessageLoop(bot).run_forever())
print('Listening ...')

loop.run_forever()
Example #32
0
        for category in highscores_categories:
            if char.get(category, None):
                highscore_string = highscore_format[category].format(
                    pronoun2, char[category], char[category + '_rank'])
                reply += "\n🏆 {0}".format(highscore_string)
        return reply

    def on_close(self, ex):
        yield from self.sender.sendMessage('Fechou')


class ChatBox(telepot.aio.DelegatorBot):
    def __init__(self, token):
        super(ChatBox, self).__init__(token, [
            pave_event_space()(per_chat_id(), create_open, Tibia, timeout=10),
        ])


#TOKEN = sys.argv[1]  # get token from command-line
TOKEN = '344437874:AAEXStWb9DM3S6FhtWC-jlWULgv-1gyoWLU'
#TOKEN = '283648340:AAE6n-MG0ZEj_5rwBypeR1aN5yp7a7W7NwY'

#bot = ChatBox(TOKEN)
bot = telepot.aio.DelegatorBot(TOKEN, [
    pave_event_space()(per_chat_id(), create_open, Tibia, timeout=10),
])
loop = asyncio.get_event_loop()
loop.create_task(bot.message_loop())
print('Listening ...')

loop.run_forever()
Example #33
0
    async def on_chat_message(self, msg):
        cid = self.chat_id

        content_type, chat_type, chat_id = telepot.glance(msg)

        if content_type != 'text':
            return

        text = msg['text']
        if not text.startswith(BOT_PREFIX):
            return

        if msg['text'] != (BOT_PREFIX + 'sub'):
            return

        SUBSCRIBED_CHAT_ID.add(cid)
        await self.sender.sendMessage('Subscribed to updates')


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

bot = telepot.aio.DelegatorBot(TOKEN, [
    pave_event_space()(per_chat_id(), create_open, Idler, timeout=10),
])

loop = asyncio.get_event_loop()
loop.create_task(MessageLoop(bot).run_forever())
print('Listening ...')

loop.run_forever()
Example #34
0
 def __init__(self, token):
     super(ChatBox, self).__init__(token, [
         pave_event_space()(per_chat_id(), create_open, Tibia, timeout=10),
     ])
Example #35
0
    chunk_size = len(lst) // chunk_count
    return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)]


'''
    keyboard = InlineKeyboardMarkup(inline_keyboard=[
        [InlineKeyboardButton(text='Press me', callback_data='4')],
    ])

    bot.sendMessage(chat_id, 'Use inline keyboard', reply_markup=keyboard)
'''

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

# bot = telepot.aio.Bot(TOKEN)

bot = telepot.aio.DelegatorBot(TOKEN, [
    pave_event_space()(
        per_chat_id(), create_open, SheluderStarter, timeout=3),
    pave_event_space()(
        per_callback_query_origin(), create_open, Sheluder, timeout=60),
])


loop = asyncio.get_event_loop()

loop.create_task(MessageLoop(bot).run_forever())
print('Listening ...')

loop.run_forever()
        if guess != self._answer:
            response = requests.get('http://numbersapi.com/' + str(guess),
                                    headers=headers,
                                    params=params)
            # give a descriptive hint
            hint = self._hint(self._answer, guess)
            await self.sender.sendMessage("try something " + hint + "\n" +
                                          response.text)
        else:
            await self.sender.sendMessage('Correct!')
            self.close()

    async def on__idle(self, event):
        await self.sender.sendMessage(
            'Game expired. The answer is %d.\n Please frequent the @VergeZoo \n Calling out  @XVGPufferfish,  @GorillaChain, @Simple_Dolphin, and @XVGHawk'
            % self._answer)
        self.close()


TOKEN = sys.argv[1]

bot = telepot.aio.DelegatorBot(TOKEN, [
    pave_event_space()(per_chat_id(), create_open, Player, timeout=60),
])

loop = asyncio.get_event_loop()
loop.create_task(MessageLoop(bot).run_forever())
print('Listening ...')

loop.run_forever()
    return web.Response(body='OK'.encode('utf-8'))

async def init(app, bot):
    app.router.add_route('GET', '/webhook', feeder)
    app.router.add_route('POST', '/webhook', feeder)

    await bot.setWebhook(URL)


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

loop = asyncio.get_event_loop()

app = web.Application(loop=loop)
bot = telepot.aio.DelegatorBot(TOKEN, [
    pave_event_space()(
        per_chat_id(), create_open, MessageCounter, timeout=10)],
    loop=loop)
webhook = OrderedWebhook(bot)

loop.run_until_complete(init(app, bot))

loop.create_task(webhook.run_forever())

try:
    web.run_app(app, port=PORT)
except KeyboardInterrupt:
    pass
Example #38
0

class MessageHandler(telepot.aio.helper.ChatHandler):
    def __init__(self, *args, **kwargs):
        super(MessageHandler, self).__init__(*args, **kwargs)

    async def on_chat_message(self, msg):
        if msg["from"]["id"] == SECRETS.CHAT_ID:
            await on_chat_Handler(msg, SECRETS.CHAT_ID)
        else:
            pass


# send telegram message
async def send_telegram_msg(msg):
    try:
        await bot.sendMessage(SECRETS.CHAT_ID, msg)
    except:
        pass


# initialize telegram
bot = telepot.aio.DelegatorBot(API_KEY, [
    pave_event_space()(per_chat_id(), create_open, MessageHandler, timeout=20),
])
loop = asyncio.get_event_loop()
loop.create_task(MessageLoop(bot).run_forever())
client.run(SECRETS.TOKEN)
print('Listening ...')
loop.run_forever()
Example #39
0
        if 'favourite' in query_data:
            download_to = query_data.strip('favourite_')
            with open(torrents_cfg['t_file_magnet'], 'rb') as hFile:
                torrent = pickle.load(hFile)
            try:
                self.command.torrent_add(torrent['torrent'],
                                         download_dir=favourites[download_to])
                await self.bot.sendMessage(from_id,
                                           "Link has been added to the queue",
                                           reply_markup=None)
                await self.show_torrents_list(from_id)
            except Exception as e:
                await self.bot.sendMessage(from_id, e, reply_markup=None)

    async def on__idle(self, event):
        await asyncio.sleep(1)
        self.close()


teletor = telepot.aio.DelegatorBot(telegram_bot['token'], [
    pave_event_space()(per_chat_id(), create_open, TorrentBot, timeout=10),
    pave_event_space()(
        per_callback_query_origin(), create_open, TorrentBot, timeout=10),
])

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.create_task(teletor.message_loop())
    loop.run_forever()
Example #40
0
           guess = int(msg['text'])
        except ValueError:
            await 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)
            await self.sender.sendMessage(hint)
        else:
            await self.sender.sendMessage('Correct!')
            self.close()

    async def on_close(self, exception):
        if isinstance(exception, telepot.exception.WaitTooLong):
            await self.sender.sendMessage('Game expired. The answer is %d' % self._answer)


TOKEN = sys.argv[1]

bot = telepot.aio.DelegatorBot(TOKEN, [
    (per_chat_id(), create_open(Player, timeout=10)),
])
loop = asyncio.get_event_loop()

loop.create_task(bot.message_loop())
print('Listening ...')

loop.run_forever()