async def initial_handler(self, msg, chat_handler): if len(Group.select().where(Group.group_name == get_config_item( "OPS_GROUP", "ncdot"))) > 0: ncdotgroup = Group.select().where( Group.group_name == get_config_item("OPS_GROUP", "ncdot")).get() if len(GroupMembership.select().where( GroupMembership.group == ncdotgroup, GroupMembership.user == chat_handler.user)) > 0: try: r = await aiohttp.get( get_config_item("OPS_JSON_URL", 'ncdotopsurl')) self._ops = (await r.json())["ops"] self.finished() if self._ops != []: await self.send_template(chat_handler, "OPS") else: await chat_handler.sender.sendMessage("No ops planned") except: traceback.print_exc() self.finished() await chat_handler.sender.sendMessage("error getting !ops") else: self.finished() await chat_handler.sender.sendMessage( "you are not in ncdot group") else: self.finished() await chat_handler.sender.sendMessage("no ncdot group")
async def group_loop(bot, loop): while True: logging.info("Starting autogroup loop") tasks = [auto_group(u) for u in User.select()] await asyncio.gather(*tasks) await asyncio.sleep(get_config_item("AUTOGROUP_INTERVAL", 60 * 5) ) # run check every 5 minutes
async def legacy_pinggroup(request): group = request.match_info.get('group', "group") text = request.match_info.get('text', "'message'") fromp = request.match_info.get('from', "'message'") tasks = [] success = 0 # look up the group, for each user id send the 'message' for member in GroupMembership.select().where( GroupMembership.group == Group.select().where( Group.legacy_name == group)): tasks.append( safe_send(member.user.telegram_id, "Ping from " + fromp + " to " + group + ":\n\n" + text)) success += 1 def chunks(l, n): for i in range(0, len(l), n): yield l[i:i + n] start_time = time.time() for chunk in chunks(tasks, get_config_item("THROTTLE_CHUNK_SIZE", 20)): await asyncio.gather(*chunk) await asyncio.sleep(1) elapsed = time.time() - start_time rounded = math.floor(elapsed * 100) / 100 msg = "Ping sent to " + str(success) + " users in " + str( rounded) + " seconds" return web.Response(body=msg.encode('utf-8'))
async def legacy_pinggroup(request): group = request.match_info.get('group', "group") text = request.match_info.get('text', "'message'") fromp = request.match_info.get('from', "'message'") tasks = [] success = 0 # look up the group, for each user id send the 'message' for member in GroupMembership.select().where(GroupMembership.group==Group.select().where(Group.legacy_name == group)): tasks.append(safe_send(member.user.telegram_id, "Ping from "+fromp+" to "+group+":\n\n"+text)) success += 1 def chunks(l, n): for i in range(0, len(l), n): yield l[i:i+n] start_time = time.time() for chunk in chunks(tasks, get_config_item("THROTTLE_CHUNK_SIZE", 20)): await asyncio.gather(*chunk) await asyncio.sleep(1) elapsed = time.time() - start_time rounded = math.floor(elapsed*100)/100 msg = "Ping sent to "+str(success)+" users in "+str(rounded)+" seconds" return web.Response(body=msg.encode('utf-8'))
async def throttle(self, tasks): def chunks(l, n): for i in range(0, len(l), n): yield l[i:i+n] for chunk in chunks(tasks, get_config_item("THROTTLE_CHUNK_SIZE", 20)): await asyncio.gather(*chunk) await asyncio.sleep(1)
async def throttle(self, tasks): def chunks(l, n): for i in range(0, len(l), n): yield l[i:i + n] for chunk in chunks(tasks, get_config_item("THROTTLE_CHUNK_SIZE", 20)): await asyncio.gather(*chunk) await asyncio.sleep(1)
async def initial_handler(self, msg, chat_handler): if len(Group.select().where(Group.group_name == get_config_item("OPS_GROUP", "ncdot"))) > 0: ncdotgroup = Group.select().where(Group.group_name == get_config_item("OPS_GROUP", "ncdot")).get() if len(GroupMembership.select().where(GroupMembership.group == ncdotgroup, GroupMembership.user == chat_handler.user))> 0: try: r = await aiohttp.get(get_config_item("OPS_JSON_URL", 'ncdotopsurl')) self._ops = (await r.json())["ops"] self.finished() if self._ops != []: await self.send_template(chat_handler, "OPS") else: await chat_handler.sender.sendMessage("No ops planned") except: traceback.print_exc() self.finished() await chat_handler.sender.sendMessage("error getting !ops") else: self.finished() await chat_handler.sender.sendMessage("you are not in ncdot group") else: self.finished() await chat_handler.sender.sendMessage("no ncdot group")
def handle_verification_code(self, msg, chat_handler): if (yield from assert_text(msg, chat_handler)): self._verification_code = msg["text"] r = re.compile("^[a-zA-Z0-9]{64}") if r.match(self._verification_code) is not None: key_details = yield from get_key_details( self._keyid, self._verification_code) if key_details is not None: if key_details["type"] == "Account": if key_details["accessMask"] & get_config_item( "API_MINIMUM_MASK", 16777216): if key_details["expires"] == "": api_key, created = ApiKey.create_or_get( user=chat_handler.user, key_id=self._keyid, verification_code=self._verification_code) if not created: self.cancel() yield from self.send_template( chat_handler, "KEY_ALREADY_EXISTS") else: self.finished() yield from self.send_template( chat_handler, "KEY_ADDED") else: self.finished() yield from self.send_template( chat_handler, "KEY_EXPIRES") else: self.finished() yield from self.send_template( chat_handler, "KEY_WRONG_MASK") else: self.finished() yield from self.send_template(chat_handler, "KEY_NOT_ACCOUNT") else: self.finished() yield from self.send_template(chat_handler, "KEY_INVALID") else: yield from self.send_template(chat_handler, "VCODE_INVALID")
def handle_verification_code(self, msg, chat_handler): if (yield from assert_text(msg,chat_handler)): self._verification_code = msg["text"] r = re.compile("^[a-zA-Z0-9]{64}") if r.match(self._verification_code) is not None: key_details = yield from get_key_details(self._keyid,self._verification_code) if key_details is not None: if key_details["type"] == "Account": if key_details["accessMask"] & get_config_item("API_MINIMUM_MASK", 16777216): if key_details["expires"] == "": api_key, created = ApiKey.create_or_get( user=chat_handler.user, key_id=self._keyid, verification_code=self._verification_code) if not created: self.cancel() yield from self.send_template(chat_handler, "KEY_ALREADY_EXISTS") else: self.finished() yield from self.send_template(chat_handler, "KEY_ADDED") else: self.finished() yield from self.send_template(chat_handler, "KEY_EXPIRES") else: self.finished() yield from self.send_template(chat_handler, "KEY_WRONG_MASK") else: self.finished() yield from self.send_template(chat_handler, "KEY_NOT_ACCOUNT") else: self.finished() yield from self.send_template(chat_handler, "KEY_INVALID") else: yield from self.send_template(chat_handler, "VCODE_INVALID")
async def group_loop(bot, loop): while True: logging.info("Starting autogroup loop") tasks = [auto_group(u) for u in User.select()] await asyncio.gather(*tasks) await asyncio.sleep(get_config_item("AUTOGROUP_INTERVAL", 60 * 5)) # run check every 5 minutes
async def legacy_parse(request): global last_message, last_message_time data = await request.post() raw = data["messages"] #remove irc formatting pattern = r'[\x02\x0F\x16\x1D\x1F]|\x03(\d{,2}(,\d{,2})?)?' raw = re.sub(pattern, '', raw) if raw[-2:] == ",]": raw = raw[:-2] + "]" parsed = [] try: parsed = json.loads(raw) except Exception: e = sys.exc_info()[0] print(e) traceback.print_exc() print(raw) r = re.compile( get_config_item("IRSSI_PING_FORMAT", "\[BROADCAST/([\w\s;]*)]\s(\w*)\:\s(.*)")) msg = "" for pingrow in parsed: #ping_time = pingrow["time"] #sender = pingrow["sender"] message = pingrow["message"] m = r.search(message) legacy_groups = m.groups()[0].split(";") legacy_sender = m.groups()[1] message = m.groups()[2] if pingrow[ "message"] != last_message or last_message_time + datetime.timedelta( minutes=30) < datetime.datetime.now(): last_message = pingrow["message"] last_message_time = datetime.datetime.now() for group in legacy_groups: group_name = group.lower().strip() tasks = [] success = 0 # look up the group, for each user id send the 'message' for member in GroupMembership.select().where( GroupMembership.group == Group.select().where( Group.legacy_name == group_name)): tasks.append( safe_send( member.user.telegram_id, "Ping from " + legacy_sender + " to " + group_name + ":\n\n" + message)) success += 1 def chunks(l, n): for i in range(0, len(l), n): yield l[i:i + n] start_time = time.time() for chunk in chunks(tasks, get_config_item("THROTTLE_CHUNK_SIZE", 20)): await asyncio.gather(*chunk) await asyncio.sleep(1) elapsed = time.time() - start_time rounded = math.floor(elapsed * 100) / 100 msg += "Ping sent to " + str( success) + " users for " + group_name + " in " + str( rounded) + " seconds\n" print(msg) return web.Response(body=msg.encode('utf-8'))
async def legacy_parse(request): global last_message, last_message_time data = await request.post() raw = data["messages"] #remove irc formatting pattern = r'[\x02\x0F\x16\x1D\x1F]|\x03(\d{,2}(,\d{,2})?)?' raw = re.sub(pattern, '', raw) if raw[-2:] == ",]": raw = raw[:-2]+"]" parsed = [] try: parsed = json.loads(raw) except Exception: e = sys.exc_info()[0] print(e) traceback.print_exc() print(raw) r = re.compile(get_config_item("IRSSI_PING_FORMAT", "\[BROADCAST/([\w\s;]*)]\s(\w*)\:\s(.*)")) msg = "" for pingrow in parsed: #ping_time = pingrow["time"] #sender = pingrow["sender"] message = pingrow["message"] m = r.search(message) legacy_groups = m.groups()[0].split(";") legacy_sender = m.groups()[1] message = m.groups()[2] if pingrow["message"] != last_message or last_message_time + datetime.timedelta(minutes=30) < datetime.datetime.now(): last_message = pingrow["message"] last_message_time = datetime.datetime.now() for group in legacy_groups: group_name = group.lower().strip() tasks = [] success = 0 # look up the group, for each user id send the 'message' for member in GroupMembership.select().where(GroupMembership.group==Group.select().where(Group.legacy_name == group_name)): tasks.append(safe_send(member.user.telegram_id, "Ping from "+legacy_sender+" to "+group_name+":\n\n"+message)) success += 1 def chunks(l, n): for i in range(0, len(l), n): yield l[i:i+n] start_time = time.time() for chunk in chunks(tasks, get_config_item("THROTTLE_CHUNK_SIZE", 20)): await asyncio.gather(*chunk) await asyncio.sleep(1) elapsed = time.time() - start_time rounded = math.floor(elapsed*100)/100 msg += "Ping sent to "+str(success)+" users for "+group_name+" in "+str(rounded)+" seconds\n" print(msg) return web.Response(body=msg.encode('utf-8'))
import logging import os import asyncio import telepot import re from jinja2 import Template from conversationhandler.strings import strings from botdata import get_config_item LOG_FILENAME = os.path.dirname(os.path.realpath(__file__)) + '/../log.txt' logging.basicConfig(filename=get_config_item("LOG_FILENAME", LOG_FILENAME), level=get_config_item("LOG_LEVEL", logging.WARNING)) _s = strings async def assert_text(msg, chat_handler): content_type, chat_type, chat_id = telepot.glance2(msg) if content_type != 'text': await chat_handler.sender.sendMessage( _s["msg_expecttext"] ) return False return True class BotCommand: def __init__(self, telegram_id, bot): self.telegram_id = telegram_id self.bot = bot
import telepot from telepot.delegate import per_chat_id from telepot.async.delegate import create_open from web import pingforward_web_init from botdata import get_config_item from conversationhandler import ConversationHandler from apipull.apipull import check_api_loop from autogroup.groupmaster import group_loop TOKEN = "154397353:AAEChVXNz7BXxenwjNokfryfZqUgiwZLN6A" class LoggedDelegatorBot(telepot.async.DelegatorBot): def __init__(self, token, delegation_patterns, loop=None): super(LoggedDelegatorBot, self).__init__(token, delegation_patterns, loop) async def sendMessage(self, chat_id, text, parse_mode=None, disable_web_page_preview=None, reply_to_message_id=None, reply_markup=None): print("[REPLY TO: "+str(chat_id)+"]:\n"+str(text)) await super(LoggedDelegatorBot, self).sendMessage(chat_id, text, parse_mode, disable_web_page_preview, reply_to_message_id, reply_markup) bot = LoggedDelegatorBot(get_config_item("TELEPOT_TOKEN", TOKEN), [ (per_chat_id(), create_open(ConversationHandler, timeout=get_config_item("TELEPOT_CONVO_TIMEOUT", 60*10))), ]) loop = asyncio.get_event_loop() loop.create_task(bot.messageLoop()) loop.create_task(check_api_loop(bot, loop)) loop.create_task(group_loop(bot, loop)) loop.create_task(pingforward_web_init(bot,loop)) loop.run_forever()
import logging import os import asyncio import telepot import re from jinja2 import Template from conversationhandler.strings import strings from botdata import get_config_item LOG_FILENAME = os.path.dirname(os.path.realpath(__file__)) + '/../log.txt' logging.basicConfig(filename=get_config_item("LOG_FILENAME", LOG_FILENAME), level=get_config_item("LOG_LEVEL", logging.WARNING)) _s = strings async def assert_text(msg, chat_handler): content_type, chat_type, chat_id = telepot.glance2(msg) if content_type != 'text': await chat_handler.sender.sendMessage(_s["msg_expecttext"]) return False return True class BotCommand: def __init__(self, telegram_id, bot): self.telegram_id = telegram_id self.bot = bot self.current_handler = self.initial_handler self.isFinished = False