Пример #1
0
def run(config):
    logging.info('start reading model file')
    with open('model.json', 'r') as f:
        model_json = f.read()

    logging.info('start reading model')
    model = markovify.Text.from_json(model_json)
    logging.info('read model')

    bot = Bot(api_token=config.token, proxy=config.proxy['proxy_url'])

    @bot.command(r"/start")
    def start(chat: Chat, match):
        keyboard = {
            "keyboard": [['Два чая, этому господину']],
            "resize_keyboard": True
        }
        return chat.send_text("В основе меня лежат цепи маркова, а обучен я на фанфиках, книгах по "
                              "программированию и ветхом завете. \n"
                              "Можешь попробовать поговорить со мной.\n"
                              "На любую вашу фразу я отвечу каким-то бредом.",
                              reply_markup=json.dumps(keyboard))

    @bot.default
    def answerer(chat, message):
        answer = model.make_sentence()
        logging.info(f"{chat.sender}, {message}: {answer}")
        return chat.reply(answer)

    channel = bot.channel(config.chanel)

    async def chanel_posting():
        while True:
            await channel.send_text(model.make_sentence())
            await asyncio.sleep(60 * config.interval)

    loop = asyncio.get_event_loop()

    bot_loop = loop.create_task(bot.loop())
    chanel_loop = loop.create_task(chanel_posting())
    loop.run_until_complete(asyncio.gather(bot_loop, chanel_loop))
    loop.close()
Пример #2
0
def run(config):
    logging.info('start reading model file')
    bot = Bot(api_token=config.token, default_in_groups=True)

    @bot.command(r"/start")
    def start(chat: Chat, match):
        return chat.send_text(
            "В основе меня лежат цепи маркова, а обучен я на фанфиках, книгах по "
            "программированию и ветхом завете. \n"
            "Можешь попробовать поговорить со мной.\n"
            "На любую вашу фразу я отвечу каким-то бредом.", )

    @bot.default
    async def answerer(chat, message):
        async with aiohttp.ClientSession() as session:
            r = await session.post(f'{config.api_uri}/phrase',
                                   json={'phrase': message.get('text', '')})
            answer = (await r.json())['answer']

        logging.info(f"{chat.sender}, {message}: {answer}")
        return chat.reply(answer)

    channel = bot.channel(config.chanel)

    async def chanel_posting():
        while True:
            async with aiohttp.ClientSession() as session:
                r = await session.post(f'{config.api_uri}/phrase',
                                       json={'phrase': ''})
                answer = (await r.json())['answer']

            await channel.send_text(answer)
            await asyncio.sleep(60 * config.interval)

    loop = asyncio.get_event_loop()

    bot_loop = loop.create_task(bot.loop())
    chanel_loop = loop.create_task(chanel_posting())
    loop.run_until_complete(asyncio.gather(bot_loop, chanel_loop))
    loop.close()
Пример #3
0
        torinfo = handle.get_torrent_info()
        if not torinfo:
            raise ValueError('magnet2torrent: failed getting torrent info')
        torfile = libtorrent.create_torrent(torinfo)
    except Exception:
        logger.exception('magnet2torrent: failed creating torrent file')
        return

    try:
        torrent_content = libtorrent.bencode(torfile.generate())
        if torrent_content:
            logger.info('magnet2torrent: done [%s]', magnet)
            return torinfo.name() + '.torrent', torrent_content
        else:
            logger.error('magnet2torrent: empty torrent content body [%s]',
                         magnet)
    except Exception:
        logger.exception('magnet2torrent: torrent generating problem [%s]',
                         magnet)


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    try:
        bots = [t2m_bot.loop(), m2t_bot.loop()]
        loop.run_until_complete(asyncio.wait(bots))
    except KeyboardInterrupt:
        t2m_bot.stop()
        m2t_bot.stop()
        loop.stop()
Пример #4
0
            return await original_api_call(method, **params)
        except ClientConnectionError:
            await asyncio.sleep(RETRY_TIMEOUT)
            return await original_api_call(method, **params)
    bot.api_call = api_call_with_handle_exceptions


if __name__ == '__main__':
    logger.setLevel(logging.DEBUG)
    logger.warning('Start RZD telegram bot...')

    # do not get down on aiohttp exceptions
    patch_bot_api_call(bot)

    loop = asyncio.get_event_loop()
    bot_future = asyncio.ensure_future(bot.loop())
    task_future = asyncio.ensure_future(process_queue())
    try:
        loop.run_until_complete(bot_future)
        # bot.run()
    except KeyboardInterrupt:
        bot_future.cancel()
        task_future.cancel()
        loop.run_until_complete(stop_bot())
        bot.stop()
        # raise
    # except:  # noqa
    #     pass
    finally:
        loop.run_until_complete(bot.session.close())
        logger.debug("Closing loop")
Пример #5
0
class TelegramAgent(Agent):
    def __init__(self, name=None):
        super().__init__(name=name)
        self._bot = Bot(api_token=TELEGRAM_BOT_API_TOKEN,
                        name=TELEGRAM_BOT_NAME,
                        api_timeout=10)
        self._bot.default(self.on_incoming_telegram_message)
        self.sent_telegram_messages = {}

    def on_incoming_telegram_message(self, chat, message):
        try:
            text = message['text']
            name = text
            if len(name) > FRAME_NAME_MAX_LENGTH:
                name = name[:FRAME_NAME_MAX_LENGTH - 1] + '…'
            full_name = '{} {}'.format(message['from']['first_name'],
                                       message['from']['last_name'])
            sent_msg = self.message(name,
                                    data={
                                        'text': text,
                                        'message_id': message['message_id'],
                                        'chat_id': message['chat']['id'],
                                        'user_id': message['from']['id'],
                                        'username':
                                        message['from']['username'],
                                        'full_name': full_name,
                                        'session': message['chat']['id'],
                                    })
            self.sent_telegram_messages.update(
                {sent_msg.id: message['chat']['id']})
        except Exception:
            print(traceback.format_exc())
            print(message.name, message.data)

    @on_message('*')
    async def telegram_message_reply(self, message):
        if message.reply_to not in self.sent_telegram_messages:
            return
        text = message.data.text or message.name
        try:
            chat_id = self.sent_telegram_messages[message.reply_to]
            # del self.sent_telegram_messages[message.reply_to]
            await self._bot.send_message(chat_id=chat_id, text=text)
            self.emit('telegram_reply_sent',
                      data={
                          'text': text,
                          'chat_id': chat_id
                      })
        except Exception:
            print(traceback.format_exc())
            print(message.name, message.data)

    @on_event('send_telegram_message')
    async def send_message(self, event):
        text = event.data.text
        chat_id = event.data.session or event.data.chat_id
        if not chat_id:
            self.emit('telegram_message_error',
                      data={'text': 'session or chat_id expected.'})
            return
        try:
            ret_val = await self._bot.send_message(chat_id=chat_id, text=text)
            self.emit('telegram_message_sent',
                      data={
                          'text': text,
                          'chat_id': chat_id,
                          'return': ret_val
                      })
        except Exception:
            print(traceback.format_exc())
            print(event.name, event.data)

    @on_event('*** started')
    def on_started(self, event):
        self.emit('telegram_connecting')
        self.spawn(self._bot.loop())

    @on_event('*** stopping')
    def on_stopping(self, event):
        self._bot.stop()
Пример #6
0
    session.pause()
    try:
        torinfo = handle.get_torrent_info()
        if not torinfo:
            raise ValueError('magnet2torrent: failed getting torrent info')
        torfile = libtorrent.create_torrent(torinfo)
    except Exception:
        logger.exception('magnet2torrent: failed creating torrent file')
        return

    try:
        torrent_content = libtorrent.bencode(torfile.generate())
        if torrent_content:
            logger.info('magnet2torrent: done [%s]', magnet)
            return torinfo.name() + '.torrent', torrent_content
        else:
            logger.error('magnet2torrent: empty torrent content body [%s]', magnet)
    except Exception:
        logger.exception('magnet2torrent: torrent generating problem [%s]', magnet)


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    try:
        bots = [t2m_bot.loop(), m2t_bot.loop()]
        loop.run_until_complete(asyncio.wait(bots))
    except KeyboardInterrupt:
        t2m_bot.stop()
        m2t_bot.stop()
        loop.stop()
Пример #7
0
class Telegram(Service):

    chats = {}

    class TelegramChat(Chat):
        def __init__(self, service, name, channel):
            super().__init__(service, name)

            self.id = "{0}/{1}/{2}".format(service.id, channel.server.name,
                                           channel.name)
            self.channel = channel

        # async def join(self):
        #     self.service.conn.send("JOIN {}".format(self.name))
        #
        async def send(self, message):
            #self.service.conn.send("PRIVMSG {0} :{1}".format(self.name, message))
            await self.service.conn.send_message(self.channel, message)

        async def receive(self, message):
            # Build context
            text = message.content
            author = message.author
            name = author.name

            if author.id == self.service.conn.user.id:
                logger.debug("{0}: Message is from us - ignoring.".format(
                    self.service.id))
            else:
                for bridge in self.bridges:
                    await bridge.receive(text, self, name)

    def __init__(self, bot, id, name, enabled, token):
        super().__init__()

        self.bot = bot
        self.id = id
        self.name = name
        self.enabled = enabled
        self.token = token

        self.logger.info("Initialising Slack bot {0}".format(id))

    def create(self):
        # Create Slack connection
        self.conn = Bot(api_token=self.token)

        # Event registration
        #self.conn.event(self.on_ready)
        #self.conn.event(self.on_message)
        self.conn.add_command(r'.*', self.on_message)

    def start(self):
        if self.enabled:
            self.create()
            return self.conn.loop()

        else:
            logger.info("{0} is currently disabled".format(self.id))
            return

    async def create_chat(self, channel, discord_channel):
        logger.debug("{0} creating chat for {1}".format(
            self.id, channel['name']))
        chat = self.DiscordChat(self, channel['name'], discord_channel)

        if 'bridges' not in channel:
            bridges = [None]
        else:
            bridges = channel['bridges']

        # Get/create bridges
        for bridge_name in bridges:
            bridge = self.bot.get_bridge(bridge_name)
            bridge.add(chat)
            chat.bridges.append(bridge)

        self.chats[chat.channel.id] = chat
        #await chat.join()
        #await chat.send("Hello {}!".format(chat.name))

    # async def on_join(self, conn, message):
    #     nick = message.prefix.nick
    #     channel = message.parameters[0]
    #     logger.debug("{0}: {1} joined {2}".format(self.id, nick, channel))
    #
    #     if nick == self.nick:
    #         # This is us
    #         logger.debug("{0}: We've joined {1}".format(self.id, channel))
    #         self.chats[channel].joined = True
    #
    # async def log(self, conn, message):
    #     logger.debug("{0}: {1}".format(self.id, message))
    #
    async def on_message(self, chat, match):
        user = chat.sender
        message = chat.message
        chat_details = message['chat']

        logger.debug(
            "{0}: message received: [{1} ({2}, {3})] {4} (@{5}) {6}".format(
                self.id, chat_details['title'], chat.id, chat.type,
                user['first_name'], user['username'], message['text']))
        #channel = message.channel.id

        #if channel in self.chats:
        #    await self.chats[channel].receive(message)
        #else:
        #    logger.debug("{0}: Ignoring message in unconfigured channel.".format(self.id))

    async def quit(self):
        logger.debug("{0}: Quitting...".format(self.id))
        self.conn.stop()
        logger.debug("{0}: Disconnected!".format(self.id))