Exemple #1
0
 def sendMessage(self, chat_id, message, **kwargs):
     return_value = None
     while True:
         try:
             Log.debug(
                 2,
                 'Calling telepot_bot.sendMessage() [chat_id = {},message = {}, kwargs = {}]',
                 chat_id, repr(message), kwargs)
             return_value = self.bot.sendMessage(chat_id, message, **kwargs)
             break
         except telepot.exception.TelegramError as e:
             # Markdown fail
             if self.fail_with_md is not None and e[-1]['error_code'] == 400 and \
              'Can\'t find end of the entity starting at byte' in e[-1]['description']:
                 # Must fail safe
                 return_value = self.bot.sendMessage(
                     chat_id, 'Error: {}\nRaw description: {}'.format(
                         self.fail_with_md, e[-1]['description']))
                 break
             else:
                 Log.error('Raise exception: {}', repr(e))
                 raise e
         except Exception as e:
             Log.error('Exception {} occurred', e.__name__)
             Log.debug(
                 1,
                 'on telepot_bot.sendMessage() [chat_id = {},message = {}, kwargs = {}]',
                 chat_id, repr(message), kwargs)
             time.sleep(self.WAIT_TIME)
     return return_value
Exemple #2
0
 def glance(self, msg):
     while True:
         try:
             Log.debug(2, 'Calling telepot.glance()')
             content_type, chat_type, chat_id = telepot.glance(msg)
             Log.debug(
                 2,
                 'Exiting telepot.glance() [content_type = {}, chat_type = {}, chat_id = {}]',
                 content_type, chat_type, chat_id)
             break
         except telepot.exception.TelegramError as e:
             Log.error('Raise exception: {}', e.__name__)
             raise e
         except Exception as e:
             Log.error('Exception {} occurred', e.__name__)
             time.sleep(0.03)
     return (content_type, chat_type, chat_id)
 def get(self, chat_id):
     try:
         Log.debug(
             2, 'Calling group_cache_class.get() [chat_id in self.g  = {}]',
             chat_id in self.g)
         Log.debug(2, '[self.g[{}] = {}]', chat_id, self.g[chat_id])
         return self.g[chat_id]
     except KeyError:
         Log.error('Can\'t find {} in get()', chat_id)
         self.add((chat_id, None, 0, 1, 0, 0, b64encode(repr([]))),
                  not_found=True)
         self.__db_add(chat_id)
         self.bot.sendMessage(
             chat_id,
             'It\'s seems that database broken, please reset welcome message.'
         )
         return {'msg': None}
Exemple #4
0
def mainRequest(LATEST):
    r = requests.get('{}/LATEST'.format(Config.backup.website), timeout=10)
    if LATEST == r.text:
        return LATEST
    _LATEST = LATEST
    LATEST = r.text
    s = requests.get('{}/{}.tar.gz'.format(Config.backup.website, LATEST),
                     stream=True,
                     timeout=10)
    try:
        s.raise_for_status()
    except Exception as e:
        Log.error('Catched Exception:`{}\'', repr(e))
        return _LATEST
    # From: https://stackoverflow.com/questions/16694907/how-to-download-large-file-in-python-with-requests-py
    with open("{}/{}.tar.gz".format(Config.backup.download_path, LATEST),
              'wb') as fout:
        for chunk in s.iter_content(chunk_size=1024):
            if not chunk: break
            fout.write(chunk)
    Log.info('{}.tar.gz downloaded.', LATEST)
    fileChecking(Config.backup.download_path)
    return LATEST
Exemple #5
0
	def onMessage(self,msg):
		content_type, chat_type, chat_id = self.glance(msg)

		# Added process
		if content_type == 'new_chat_member' and msg['new_chat_participant']['id'] == self.getid():
			self.gcache.add((chat_id, None, 0, 1, 0, 0, b64encode(repr([]))))
			with MainDatabase() as db:
				try:
					db.execute("INSERT INTO `welcomemsg` (`group_id`) VALUES (%d)"%chat_id)
				except MySQLdb.IntegrityError as e:
					if e[0] == 1062:
						Log.error('IntegrityError:{}', e[1])
					else:
						traceback.print_exc()
						raise e
			self.sendMessage(chat_id,'Please use /setwelcome to set welcome message',
				reply_to_message_id=msg['message_id'])
			return

		# kicked process
		elif content_type == 'left_chat_member' and msg['left_chat_member']['id'] == self.getid():
			self.gcache.delete(chat_id)
			return

		# Main process
		elif msg['chat']['type'] in group_type:
			if content_type == 'text':
				get_result = self.gcache.get(chat_id)
				result = botcommand_match.match(msg['text'])
				try:
					EntryCheck = 'entities' in msg and len(msg['entities']) > 0 and \
						msg['entities'][0]['type'] == 'bot_command'
				except IndexError:
					EntryCheck = False
					Log.warn('Catched IndexError, msg={}', repr(msg))

				if EntryCheck:
					if get_result['noblue'] and \
						(not result or result.group(1) not in self.gcache.get(chat_id)['except']):
						delete_target_message(chat_id, msg['message_id']).start()

					# Match bot command check
					if command_match.match(msg['text']) or noparmcommand_match.match(msg['text']):

						if msg['from']['id'] == Config.bot.owner:
							result = re.match(r'^\/d( (-?\d+))?$', msg['text'])
							if result:
								operid = chat_id if result.group(1) is None else result.group(2)
								self.gcache.delete(operid)
								self.gcache.add((operid, None, 0, 1, 0, 0, b64encode(repr([]))), not_found=True)
								delete_target_message(chat_id,
									self.sendMessage(chat_id, 'Operaction completed!', 
										reply_to_message_id=msg['message_id'])['message_id']).start()
								return

							result = re.match(r'^\/l$', msg['text'])
							if result:
								self.bot.leaveChat(chat_id)
								return

							result = setflag2command_match.match(msg['text'])
							if result:
								if str(result.group(2)) in flag_type:
									self.gcache.editflag((chat_id,str(result.group(2)),int(result.group(3))))
									delete_target_message(chat_id, self.sendMessage(chat_id, 'Operation completed!',
										reply_to_message_id=msg['message_id'])['message_id']).start()

						# Match /poem command
						result = poemcommand_match.match(msg['text'])
						if result:
							if get_result['poemable']:
								result = self.pcache.get()
								if not result:
									result = b64encode('TBD')
								self.bot.sendChatAction(chat_id, 'typing')
								time.sleep(3)
								self.sendMessage(chat_id, b64decode(result),
									reply_to_message_id=msg['message_id'])
								return
							elif not get_result['ignore_err']:
								self.sendMessage(chat_id, 'Permission Denied.\n*你没有资格念他的诗,你给我出去*',
										parse_mode='Markdown', reply_to_message_id=msg['message_id'])
								return
							return

						# Other command need admin privilege, check it.
						if self.getChatMember(chat_id, msg['from']['id'])['status'] not in admin_type:
							if not get_result['ignore_err']:
								self.sendMessage(chat_id, 'Permission Denied.\n你没有权限,快滚',
									reply_to_message_id=msg['message_id'])
							if self.gcache.get_is_admin(chat_id):
								self.bot.restrictChatMember(chat_id, msg['from']['id'], until_date=msg['date']+60)
							return

						# Match /setwelcome command
						result = setcommand_match.match(msg['text'])
						if result:
							welcomemsg = str(result.group(2))
							result = gist_match.match(welcomemsg)
							if result:
								r = urllib2.urlopen(welcomemsg)
								welcomemsg = r.read()
								r.close()
							if len(welcomemsg) > 4096:
								self.sendMessage(chat_id, "*Error*:Welcome message is too long.(len() must smaller than 4096)",
									parse_mode='Markdown', reply_to_message_id=msg['message_id'])
								return
							self.gcache.edit((chat_id, b64encode(welcomemsg)))
							self.sendMessage(chat_id, "*Set welcome message to:*\n%s"%welcomemsg,
								disable_web_page_preview=True, parse_mode='Markdown', reply_to_message_id=msg['message_id'])
							return

						# Match /clear command
						result = clearcommand_match.match(msg['text'])
						if result:
							self.gcache.edit((chat_id, None))
							self.sendMessage(chat_id, "*Clear welcome message successfully!*",
								parse_mode='Markdown', reply_to_message_id=msg['message_id'])
							return

						# Match /reload command
						result = reloadcommand_match.match(msg['text'])
						if result :
							if msg['from']['id'] != Config.bot.owner:
								self.sendMessage(chat_id, "*Please contant owner to reload configuration*",
									parse_mode='Markdown', reply_to_message_id=msg['message_id'])
								return
							self.gcache.load()
							self.pcache.reload()
							self.sendMessage(chat_id, "*Reload configuration and poem completed!*",
								parse_mode='Markdown', reply_to_message_id=msg['message_id'])
							return

						# Match /setflag command
						result = setflagcommand_match.match(msg['text'])
						'''
							result.group(2) is `flag name',
							result.group(3) is `flag value'
						'''
						if result:
							self.bot.sendChatAction(chat_id, 'typing')
							if str(result.group(2)) not in flag_type:
								if not get_result['ignore_err']:
									self.sendMessage(chat_id, "*Error*: Flag \"%s\" not exist"%str(result.group(2)),
										parse_mode='Markdown', reply_to_message_id=msg['message_id'])
								return
							self.gcache.editflag((chat_id, str(result.group(2)), int(result.group(3))))
							delete_target_message(chat_id, self.sendMessage(chat_id, "*Set flag \"%s\" to \"%d\" success!*"%(str(result.group(2)), int(result.group(3))),
								parse_mode='Markdown', reply_to_message_id=msg['message_id'])['message_id']).start()
							return

						result = exceptcommand_match.match(msg['text'])
						if result:
							if result.group(1) == 'd':
								if self.gcache.except_(chat_id, result.group(3), True):
									sendMessage_and_delete(chat_id, 'Delete except command success', msg['message_id'])
								else:
									sendMessage_and_delete(chat_id, 'Delete except command fail. (Is command in except list? Tips: try using /status to see more)', msg['message_id'])
							else:
								if self.gcache.except_(chat_id, result.group(3)):
									sendMessage_and_delete(chat_id, 'Add except command success', msg['message_id'])
								else:
									sendMessage_and_delete(chat_id, 'Add except command fail with excpet list too long.', msg['message_id'])
							return

						# Match /status command
						if statuscommand_match.match(msg['text']):
							delete_target_message(chat_id, self.sendMessage(chat_id, gen_status_msg(self.gcache.get(chat_id)), reply_to_message_id=msg['message_id'])['message_id']).start()
							return

						# Finally match /ping
						if pingcommand_match.match(msg['text']):
							self.sendMessage(chat_id, '*Current chat_id:* `{}`\n*Your id:* `{}`\n*Bot runtime: {}\nSystem load avg: {}*'.format(
								chat_id, msg['from']['id'], Log.get_runtime(), getloadavg()),
								parse_mode='Markdown', reply_to_message_id=msg['message_id'])['message_id'], 10)

			elif content_type in content_type_concerned:
				result = self.gcache.get(chat_id)['msg']
				if result:
					self.sendMessage(chat_id, b64decode(result).replace('$name', username_splice_and_fix(msg['new_chat_participant'])),
						parse_mode='Markdown', disable_web_page_preview=True, reply_to_message_id=msg['message_id'])
 def delete(self, chat_id):
     try:
         del self.g[chat_id]
         self.__db_del(chat_id)
     except KeyError:
         Log.error('Can\'t find {} in delete()', chat_id)