async def run(config): interval = int(config.interval) client = motor.motor_asyncio.AsyncIOMotorClient(config.mongo_url) db = client.memes_db collection = db.test_collection session = TokenSession(config.vk.token) api = API(session) bot = Bot(api_token=config.token, proxy=config.proxy['proxy_url']) channel = bot.channel("@MemesAggregation") while True: logging.info('Start checking groups') for group in config.vk.groups: asyncio.sleep(1) r = await api('wall.get', domain=group) for item in r['items']: if len(item['attachments'] ) == 1 and item['marked_as_ads'] == 0 and item[ 'attachments'][0]['type'] == 'photo': url = item['attachments'][0]['photo']['photo_604'] name = re.findall('(?=\w+\.\w{3,4}$).+', url)[0] if await collection.find_one({'name': name}) is None: logging.info('Found new meme') collection.insert_one({'name': name}) # TODO: Make it async urllib.request.urlretrieve(url, f"data/images/{name}") await channel.send_photo( photo=open(f"data/images/{name}", "rb")) os.remove(f"data/images/{name}") logging.info('Groups checked, waiting for next time...') await asyncio.sleep(interval)
class TelegramNotifier: last_request = None def __init__(self, api_token, channel): """ :param api_token: bot api token :param channel: linke @yourchannel """ from aiotg import Bot, Chat self.bot = Bot(api_token=api_token) self.channel = self.bot.channel(channel) @self.bot.command(r"/last") async def last(chat: Chat, match): if self.last_request is None: self.last_request = datetime.now() if self.last_request - datetime.now() < 30: # ignore and stop flood self.last_request = datetime.now() return self.last_request = datetime.now() engine = self.init_data_dict['engine'] from banks_licences.database import get_last from banks_licences.models import BankSanction rows = await get_last(engine, BankSanction.__table__, orderby='date') if len(rows): await self.notify(rows) async def start(self, init_data_dict: dict): self.init_data_dict = init_data_dict async def notify(self, data_list: list): decline_list = [] for data_item_dict in data_list: decline_list.append('{date} "{bank}" {link}\r\n'.format( bank=data_item_dict["name"], date=data_item_dict["date"], link=data_item_dict["url"])) try: await self.channel.send_text( 'Отозваны лицензии:\r\n\r\n{banks}'.format( banks='\r\n'.join(decline_list))) except aiohttp.client_exceptions.ClientConnectorError as e: logger.exception('unable to notify') raise RuntimeError('Unable to notify Telegram dest')
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()
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()
import os import asyncio from aiotg import Bot bot = Bot(api_token="API_TOKEN") channel = bot.channel(os.environ["CHANNEL"]) private = bot.private(os.environ["PRIVATE"]) async def greeter(): await channel.send_text("Hello from channel!") await private.send_text("Why not say hello directly?") loop = asyncio.get_event_loop() loop.run_until_complete(greeter())
class PytrackTelegramBot(object): def __init__(self): self.connection = Connection(YOUTRACK_BASE_URL, login=YOUTRACK_LOGIN, password=YOUTRACK_PASSWORD) self.bot = Bot(TELEGRAM_API_KEY) self.db_pool = None self.update_timer = None self.logger = logging.getLogger('TG-bot') async def init(self): """ Initializes app """ self.logger.info("Initializing") self.db_pool = await db.create_pool(POSTGRESQL_DSN) projects = await self.connection.get_projects() _users = await self.connection.get_users() users = [] for _user in _users: user = await self.connection.get_user(_user['login']) users.append((user['login'], user['fullName'])) async with self.db_pool.acquire() as conn: await db.ensure_projects_are_present(conn, projects) await db.ensure_users_are_present(conn, users) async def run(self): #self.logger.info("Starting timer") #self.update_timer = aiotools.create_timer( # self.check_for_updates, 300.0) await self.check_for_updates(30) async def shutdown(self): self.logger.info("Shutting down") del self.bot await self.db_pool.close() if self.update_timer: self.update_timer.cancel() await self.update_timer def create_mention(self, user): if user['tg_id']: return "[%s](tg://user?id=%s)" % (user['full_name'], user['tg_id']) else: return "@%s" % user['youtrack_id'] def create_issue_link(self, issue_id): return "[{0}]({1}/issue/{0})".format(issue_id, YOUTRACK_BASE_URL) def render_message(self, mention, comment): return MESSAGE_TEMPLATE % (mention, self.create_issue_link( comment['issueId']), comment['text']) def render_change_message(self, mention, issue, change): updated_tmpl = "- {0}: {1} -> {2}" updates = (updated_tmpl.format( field.name, field.old_value[0] if field.old_value else "n/a", field.new_value[0] if field.new_value else "n/a") for field in change.fields) updates = "\n".join(updates) return MESSAGE_CHANGE_TEMPLATE % ( mention, self.create_issue_link(issue['id']), updates) async def try_post_markdown(self, chat, message): try: await chat.send_text(message, parse_mode='Markdown') except BotApiError: self.logger.warning( "Cannot send message '%s' as markdown, resending as text", message) await chat.send_text(message) async def post_comment(self, comment): async with self.db_pool.acquire() as conn: project_id = comment['issueId'].split('-')[0] chat_id = await db.get_project_chat_id(conn, project_id) user = await db.get_user(conn, comment['author']) mention = self.create_mention(user) message = self.render_message(mention, comment) self.logger.info("Posting comment %s to chat %s", comment['id'], chat_id) chat = self.bot.channel(chat_id) await self.try_post_markdown(chat, message) await db.set_comment_posted(conn, comment) async def post_change(self, issue, change): async with self.db_pool.acquire() as conn: project_id = issue['id'].split('-')[0] chat_id = await db.get_project_chat_id(conn, project_id) user = await db.get_user(conn, change.updater_name) mention = self.create_mention(user) message = self.render_change_message(mention, issue, change) self.logger.info("Posting issue %s change to chat %s", issue['id'], chat_id) chat = self.bot.channel(chat_id) await self.try_post_markdown(chat, message) async def post_new_issue(self, issue): async with self.db_pool.acquire() as conn: project_id = issue['id'].split('-')[0] user = await db.get_user(conn, issue['reporterName']) chat_id = await db.get_project_chat_id(conn, project_id) mention = self.create_mention(user) issue_link = self.create_issue_link(issue['id']) summary = issue['summary'] issue_type = issue['Type'] assignee = issue.get('Assignee', None) assignee_mention = None if assignee: try: assignee_mention = self.create_mention(await db.get_user( conn, assignee)) except: self.logger.warning("Could not create assignee mention") if assignee_mention: message = f"{mention} создал задачу {issue_link}: {summary} с типом {issue_type}. Задача назначена на {assignee_mention}." else: message = f"{mention} создал задачу {issue_link}: {summary} с типом {issue_type}." chat = self.bot.channel(chat_id) await self.try_post_markdown(chat, message) async def check_issue(self, issue, last_updated): self.logger.info("Checking issue %s", issue['id']) last_checked = 0 project_id = issue['id'].split('-')[0] async with self.db_pool.acquire() as conn: created = int(issue['created']) if created > last_updated: # new issue last_checked = max(last_checked, created) await self.post_new_issue(issue) if issue['commentsCount']: comments = await self.connection.get_comments(issue['id']) for comment in comments: posted = await db.check_comment(conn, comment) if posted: continue updated = comment.get('updated', comment.get('created', '0')) updated = int(updated) if updated <= last_updated: self.logger.info('Skipping old comment %s', comment['id']) continue last_checked = max(last_checked, updated) await self.post_comment(comment) changes = await self.connection.get_changes_for_issue(issue['id']) for change in changes: print(change) updated = int(change.updated) if updated <= last_updated: self.logger.info('Skipping old change for issue %s', issue['id']) continue last_checked = max(last_checked, updated) await self.post_change(issue, change) if last_checked > 0: last_checked = datetime.datetime.fromtimestamp(last_checked / 1000) await db.set_last_updated(conn, project_id, last_checked) async def check_project(self, project, limit=50): self.logger.info("Checking project %s", project['youtrack_id']) try: timestamp = project['last_checked'].timestamp() current = 0 while True: issues = await self.connection.get_issues( project['youtrack_id'], project['search_query'], current, limit, updated_after=int(timestamp * 1000) if timestamp > 0 else None) self.logger.info("Got %s issues in project %s", len(issues), project['youtrack_id']) current += limit issues_tasks = list( self.check_issue(issue, timestamp * 1000) for issue in issues) if issues_tasks: await asyncio.wait(issues_tasks) if len(issues) < limit: break except ssl.SSLError: self.logger.exception('SSLError') return except youtrack.YouTrackException as ex: self.logger.exception('Youtrack exception') return async def check_for_updates(self, interval): """ Iterates over projects looking for updated issues """ self.logger.info("Checking projects for updates") try: async with self.db_pool.acquire() as conn: tasks = [] for project in await db.get_projects(conn): tasks.append(self.check_project(project)) await asyncio.wait(tasks) except asyncio.CancelledError: self.logger.info("cancelled") self.logger.info("Done")
也可以搭配`type`指令,像這樣: ```棒棒勝>洨安之歌 type:flac``` 輸入 `/stats` 來獲取 bot 資訊。 用 `/music` 指令來在群聊內使用棒棒勝 Music Bot,像這樣: ```/music 棒棒勝``` """ not_found = """ 找不到資料 :/ """ bot = Bot(api_token=os.environ.get('API_TOKEN'), name=os.environ.get('BOT_NAME'), botan_token=os.environ.get("BOTAN_TOKEN")) logger = logging.getLogger("musicbot") channel = bot.channel(os.environ.get('CHANNEL')) @bot.handle("audio") async def add_track(chat, audio): if (str(chat.sender) == 'N/A'): sendervar = os.environ.get('CHANNEL_NAME') else: sendervar = str(chat.sender) if (await db.tracks.find_one({"file_id": audio["file_id"]})): await chat.send_text("資料庫裡已經有這首囉 owo") logger.info("%s 傳送了重複的歌曲 %s %s", sendervar, str(audio.get("performer")), str(audio.get("title"))) await bot.send_message( os.environ.get("LOGCHN_ID"), sendervar + " 傳送了重複的歌曲 " + str(audio.get("performer")) + " - " + str(audio.get("title")))
# Contacts from commands.contacts import process_contact # Inline queries from commands.inline import process_inline_query # Variables api_token = os.environ.get('API_TOKEN') bot_name = os.environ.get('BOT_NAME') # Bot bot = Bot(api_token=api_token, name=bot_name) # Channel channel = bot.channel(os.environ.get('CHANNEL_NAME', '@VodiyBozorTest')) # Logging logger = logging.getLogger('bot') logging.basicConfig(level=logging.DEBUG) @bot.command(r'/start') @bot.command(r'/on') async def start(chat, match): await process_start_command(chat, match, logger) await process_ads_command(chat, match, logger) @bot.command(r'/ads') async def ads(chat, match):
import os import asyncio from aiotg import Bot bot = Bot(os.environ["API_TOKEN"]) channel = bot.channel(os.environ["CHANNEL"]) private = bot.private(os.environ["PRIVATE"]) async def greeter(): await channel.send_text("Hello from channel!") await private.send_text("Why not say hello directly?") loop = asyncio.get_event_loop() loop.run_until_complete(greeter())