def create_chat(request, content, speaker=None): chat = Chat() chat.user = speaker if speaker else request.user chat.content = linkify(clean(content, tags=list()), parse_email=True, callbacks=[callbacks.nofollow, callbacks.target_blank]) return chat
def handleEvent(tag: Tag, chat: Chat): chat.push( Event( int(tag.get('id').replace('message', '')), tag.find('div', attrs={ 'class': 'body details' }).getText().strip()))
def set_region(lib): uid = lib.message.chat.id Chat.set_config(uid, "region", lib.data) bot.reply_to(lib.message, "%s seleccionada" %lib.data) #"br", "eune", "euw", "jp", "kr", "lan", "las", "na", "oce", "tr", "ru", "pbe"
def game_play(message): chat_id = message.chat.id reply = bot.send_message(chat_id, "Adivina el número que he pensado del 1 al 100") number = randint(1, 10) Chat.set(chat_id, "game_number", number) Chat.set(chat_id, "game_steps", 1) bot.register_next_step_handler(reply, game_process_response)
def main() -> float: def __calculatePercentageOfSuccess__(stat: List[bool]) -> float: return reduce(lambda acc, cur: acc + 1 if cur else acc, stat, 0) / len(stat) * 100 try: ''' plotContributionInChatByUser(Chat.importFromText( './data/private.txt'), './plots/participationInPrivateChatByUser.png', 'Visualization of Participation of Users in Chat'), plotContributionInChatByUser(Chat.importFromText( './data/group.txt'), './plots/participationInGroupChatByUser.png', 'Visualization of Participation of Users in Chat'), *reduce(lambda acc, cur: [plotContributionOfUserByHour( cur.messages, './plots/contributionInPrivateChatOf{}ByHour.png'.format( shadeContactName('_'.join(cur.name.split(' ')), percent=75)), 'Visualization of {}\'s Participation in Private Chat'.format(shadeContactName(cur.name, percent=75)))] + acc, Chat.importFromText('./data/private.txt').users, []), *reduce(lambda acc, cur: [plotContributionOfUserByHour( cur.messages, './plots/contributionInGroupChatOf{}ByHour.png'.format( shadeContactName('_'.join(cur.name.split(' ')), percent=75)), 'Visualization of {}\'s Participation in Group Chat'.format(shadeContactName(cur.name, percent=75)))] + acc, Chat.importFromText('./data/group.txt').users, []), ''' return __calculatePercentageOfSuccess__([ *reduce( lambda acc, cur: [ plotActivityOfUserByMinute( cur.messages, './plots/detailedActivityOf{}InPrivateChatByMinute.svg' .format( shadeContactName('_'.join(cur.name.split(' ')), percent=75) ), 'Activity Of {} in Private Chat By Minute'.format( shadeContactName(cur.name, percent=75))) ] + acc, Chat.importFromText('./data/private.txt').users, []), *reduce( lambda acc, cur: [ plotActivityOfUserByMinute( cur.messages, './plots/detailedActivityOf{}InGroupChatByMinute.svg'. format( shadeContactName('_'.join(cur.name.split(' ')), percent=75) ), 'Activity Of {} in Group Chat By Minute'.format( shadeContactName(cur.name, percent=75))) ] + acc, Chat.importFromText('./data/group.txt').users, []) ]) except Exception: return 0.0
def save(message): """ Guarda un dato en el chat que se puede recuperar después """ data = util.extract_arguments(message.text) if not data: bot.reply_to(message, "Debe indicar el dato que quiere que guarde") return chat_id = message.chat.id Chat.set_config(chat_id, 'memory', data) bot.reply_to(message, "Dato guardado. Usa /load para recuperar")
def extractMinuteBasedTrafficByUser(chat: Chat, user: str) -> Counter: userObj = chat.getUser(user) return _fillUpEmptyMinuteSlotsWithZeroTrafficDenotation( Counter( map( lambda e: datetime.combine( date(2000, 1, 1), e.getTime.replace( minute=(e.getTime.minute + 1) if e.getTime.minute < 59 else e.getTime.minute, second=0) if e.getTime.second >= 30 else e.getTime. replace(second=0)), chain( map(lambda e: chat.getActivity(e), userObj.messageIDs), map(lambda e: chat.getActivity(e), userObj.getViaBotMessageIds)))))
def game_process_response(message): chat_id = message.chat.id number = int(Chat.get(chat_id, 'game_number')) steps = int(Chat.get(chat_id, 'game_steps')) guess_number = int(message.text) if (number == guess_number): bot.send_message(chat_id, f"Enhorabuena has acertado en {steps} pasos") return if (guess_number > number): reply = bot.send_message(chat_id, "El número es más pequeño") else: reply = bot.send_message(chat_id, "El número es más grande") Chat.set(chat_id, "game_steps", 1 + steps) bot.register_next_step_handler(reply, game_process_response)
def parseChat(targetPath: str) -> Chat: chat = Chat() last_msg_with_author = None for i in getChatFiles(targetPath): for j in getAllActivities( BeautifulSoup(getFileContent(i), features='lxml')): if routeToProperHandler(j, last_msg_with_author, chat): last_msg_with_author = j return chat
def summoner(message): name = util.extract_arguments(message.text) if not name: bot.send_message(message.chat.id, "Especifique un nombre de invocador") else: cid = chat_id = message.chat.id region = Chat.get_config(cid, "region") if region is None: bot.send_message( message.chat.id, "Utiliza /region para seleccionar una region primero") else: url = 'https://' + region.value + '.api.riotgames.com/lol/summoner/v4/summoners/by-name/' + name params = {'api_key': RIOT_KEY} r = requests.get(url, params) if (r.status_code in range(200, 299)): #Request accepted content = r.json() summonerId = content["id"] url = 'https://' + region.value + '.api.riotgames.com/lol/league/v4/positions/by-summoner/' + summonerId r = requests.get(url, params) contentLeague = r.json() text = "*Nombre:* " + str( content["name"]) + "\n*Nivel:* " + str( content["summonerLevel"]) + "\n" text += "*SoloQ:* " + contentLeague[0][ "tier"] + " " + contentLeague[0]["rank"] + " -> " + str( contentLeague[0]["leaguePoints"]) + " LP\n" text += " *Victorias:* " + str( contentLeague[0]["wins"]) + "\n" text += " *Derrotas:* " + str( contentLeague[0]["losses"]) + "\n\n" url = 'https://' + region.value + '.api.riotgames.com/lol/champion-mastery/v4/champion-masteries/by-summoner/' + summonerId r = requests.get(url, params) contentChamp = r.json() champ = "" with open('champion.json') as json_file: file = json.load(json_file) champion_list = file['data'] for champion_name in champion_list.keys(): if champion_list[champion_name]['key'] == str( contentChamp[0]["championId"]): champ += champion_list[champion_name]['name'] text += "*Mejor campeón:* " + champ bot.send_message(message.chat.id, text, parse_mode="Markdown") else: #Request error bot.send_message(message.chat.id, "Invocador desconocido")
def load(message): """ Recupera un dato guardado con save """ chat_id = message.chat.id data = Chat.get_config(chat_id, 'memory') if not data: bot.reply_to(message, "Aún no has guardado nada") return bot.reply_to(message, "Dato recuperado: %s" % data.value)
def extractMinuteBasedTraffic(chat: Chat) -> Counter: return _fillUpEmptyMinuteSlotsWithZeroTrafficDenotation( Counter( map( lambda e: datetime.combine( date(2000, 1, 1), e.getTime.replace( minute=(e.getTime.minute + 1) if e.getTime.minute < 59 else e.getTime.minute, second=0) if e.getTime.second >= 30 else e.getTime. replace(second=0)), filter(lambda e: not chat.isEvent(e.index), chat.activities))))
def create_index(table_name, field_name, index_name, unique=False, order=False): """创建索引""" if unique == False: if order == 'desc' or order == 'asc': Chat.raw( "CREATE INDEX {index_name} ON {table_name}({field_name} {order})" .format( **{ "index_name": index_name, "table_name": table_name, "field_name": field_name, "order": order })).execute() else: Chat.raw("CREATE INDEX {index_name} ON {table_name}({field_name})". format( **{ "index_name": index_name, "table_name": table_name, "field_name": field_name })).execute() else: if order == 'desc' or order == 'asc': Chat.raw( "CREATE UNIQUE INDEX {index_name} ON {table_name}({field_name} {order})" .format( **{ "index_name": index_name, "table_name": table_name, "field_name": field_name, "order": order })).execute() else: Chat.raw( "CREATE UNIQUE INDEX {index_name} ON {table_name}({field_name})" .format( **{ "index_name": index_name, "table_name": table_name, "field_name": field_name })).execute()
def get_chat_content(customer_id, direction): key = "{customer_id}-{direction}".format(**{ "customer_id": customer_id, "direction": direction }) content = r.get(key) print("content", content) if content: return "redis", content else: chat_objs = Chat.select().where(Chat.customer_id == customer_id, Chat.direction == direction).order_by( Chat.gen_time.desc()) datalist = [{ "id": obj.id, "customer_id": obj.customer_id, "direction": obj.direction, "content": obj.content, "gen_time": str(obj.gen_time)[:19] } for obj in chat_objs] r.set(key, json.dumps(datalist), ex=5) return "数据库", datalist
def get_chat_prices(self, plan): if plan == 'lite': column_number = 2 elif plan == 'team': column_number = 3 elif plan == 'professional': column_number = 4 elif plan == 'enterprise': column_number = 5 else: raise ValueError('Unrecognized chat plan "%s"' % plan) # get only 3 first cells which belong to "Zendesk Chat Pricing" section column_selector = 'tr:not(.compare-table-key):not(.compare-table-header) td:nth-of-type(%s) span' % column_number price_column = self.app.wd.find_elements_by_css_selector( column_selector)[:3] prices = [cell.text for cell in price_column] # string slicing is needed to remove currency sign (it is user locale dependant) return Chat(yr_price=prices[0][1:], mnth_price=prices[1][1:], agents=prices[2])
import os.path import json from model.chat import Chat data_file_name = 'chat_plans.json' path_to_data_file = os.path.join(os.path.dirname((os.path.abspath(__file__))), data_file_name) with open(path_to_data_file) as f: data = json.load(f) expected_data = dict( zip(['lite', 'team', 'professional', 'enterprise'], [ Chat(yr_price=plan['annually'], mnth_price=plan['monthly'], agents=plan['total_agents']) for plan in data.values() ]))
def region(message): uid = message.chat.id data = Chat.get_config(uid, "region") if data is not None: bot.reply_to(message, "%s actualmente seleccionada" %data.value) region_board(message)
def getTopXParticipantsAlongWithContribution(x: int, chat: Chat) -> Dict[str, float]: _tmp = chat.totalMessageCount return dict(map(lambda e: (e, chat.getUser(e).totalMessageCount / _tmp * 100), chat.getTopXParticipants(x)))
def perform_command(command: str, params: str, reply: BaseReply, locale): try: chat = Chat.get_chat(str(reply.get_chat_id()), str(reply.get_chat_type())) if command == "get_current_schedule": if len(params) == 0: if chat: schedule = get_schedule(chat.get_group().group_id) else: reply.send_text(locale['chat_is_not_registered']) return else: schedule = get_schedule(params[0]) reply.send_text( get_prettified_schedule(locale, schedule, get_today_schedule)) if command == "get_tomorrow_schedule": if chat: schedule = get_schedule(chat.get_group().group_id) else: reply.send_text(locale['chat_is_not_registered']) return reply.send_text( get_prettified_schedule(locale, schedule, get_tomorrow_schedule)) if command == "building_info": if len(params) == 0: reply.send_text(locale.message_building_not_found()) else: try: # TODO: Fix bug with commands here reply.send_text(locale.localize_building(params[0])) except KeyError: reply.send_text(locale.message_building_not_found()) if command == "uptime": start_time = open_global_pref('start_time', None) diff_time = time() - start_time hours = int(diff_time / 3600) minutes = int((diff_time - hours * 3600) / 60) seconds = int((diff_time - hours * 3600 - minutes * 60)) reply.send_text(locale['uptime_template'].format(hours=hours, minutes=minutes, seconds=seconds)) if command == "absent": is_done = chat.add_student(reply.get_message_author_name(), reply.get_message_author(), reason=params) if is_done: reply.send_text(locale['done_absent']) else: reply.send_text(locale['cant_absent']) if command == "deabsent": is_done = chat.remove_student(reply.get_message_author()) if is_done: reply.send_text(locale['done_deabsent']) else: reply.send_text(locale['didnt_deabsent']) if command == "absent_list": resp_list, date = chat.generate_absent_list( locale['default_list_content'], locale['row_template']) if resp_list: reply.send_text(locale['list_template'].format( date=date, content=resp_list)) else: reply.send_text(locale['cant_make_list']) if command == "register_chat": group_id = params.strip() if Chat.register_chat(str(reply.get_chat_id()), reply.get_chat_type(), group_id): reply.send_text(locale['registered'].format(group_id=group_id)) else: reply.send_text( locale['group_has_changed'].format(group_id=group_id)) if command == "help": content = '\n'.join( map( lambda command: help_command( locale["commands"][command]["commands"][0], locale["commands"][command]["explanation"], locale[ "row_help_template"]), locale["commands"].keys())) reply.send_text( locale['help_message'].format(help_message=content)) if command == "group": reply.send_text(locale["group_template"].format( group=chat.get_group().group_id)) except NoSchedule: reply.send_text(locale['group_not_found'])
def sendMessage(): ''' example post request: { "currentUser_displayName": "Manmohan", "receiver_displayName": "Bala", "sender_phoneNum": "9023051078", "receiver_phoneNum": "7009600580", "receiver_countryPhoneCode":"91", "message":"Be grateful to the great Thanos." } ''' req_json = request.get_json() ''' 1 sender_displayName = req_json['currentUser_displayName'] receiver_displayName = req_json['receiver_displayName'] sender_phoneNum = req_json['sender_phoneNum'] ''' sender_id = req_json['sender_id'] receiver_id = req_json['receiver_id'] receiver_countryPhoneCode = req_json['receiver_countryPhoneCode'] receiver_phoneNum = req_json['receiver_phoneNum'] message = req_json['message'] ''' 1. Hit the user table get customerId API key 2. send the sms 3. save message in chat table with sender and receiver 4. optional: do a getrequest to check whether user has received the message ''' # fetching from the database session = Session() ''' 1 user_objects = session.query( Users.telesign_customer_id, Users.telesign_api_key, Users.user_id ).\ filter(Users.display_name.like(sender_displayName) & Users.phone_number.like(sender_phoneNum)).all() ''' user_objects = session.query( Users.telesign_customer_id, Users.telesign_api_key, Users.user_id ).\ filter(Users.user_id.like(sender_id)).all() APIkey = user_objects[0].telesign_api_key customerID = user_objects[0].telesign_customer_id ''' 2 sender_id = user_objects[0].user_id ''' ''' 3 fetch receiver_id_fk by querying user table Save message data receiver_objects = session.query( Users.user_id ).\ filter(Users.display_name.like(receiver_displayName) & Users.phone_number.like(receiver_phoneNum)).all() receiver_id = receiver_objects[0].user_id ''' iMessage = Chat(message=message, sender_id_fk=sender_id, receiver_id_fk=receiver_id) session.add(iMessage) session.commit() # serializing as JSON session.close() #customerID = '0E09D1B5-86CB-4E89-828E-CA61C850BA06' #APIkey = 'M4hajYKMhoXrFnXsg84yMm+FeeSU8Jjoi3JMZVOiMysXXpPvnBv+pxNTss++zrobMxGSc8lcN8ib4elemPPBHw==' url = 'https://rest-ww.telesign.com/v1/messaging' #phoneNumber = '919023051078' #message = 'Hi I want to order pepperoni pizza' messagetype = 'ARN' data = { 'phone_number': receiver_countryPhoneCode + receiver_phoneNum, 'message': message, 'message_type': messagetype } encode = (customerID + ':' + APIkey).encode('utf-8') b64encoded = base64.urlsafe_b64encode(encode).decode('ascii') header = {'Authorization': 'Basic ' + b64encoded} response = post(url, data=data, headers=header) jsonResponse = json.loads(response.content) print(jsonify(jsonResponse)) ''' json to be returned having Message-sent: yes Timestamp : dd-mm-yy hh:mm Error: only if there is some error otherwise empty In DB save: message from phone To phone Timestamp ''' return jsonify(jsonResponse)
def insert_data_10000(): Chat.insert_many(datalist).execute()
def insert_data_1000(): for i in range(10): Chat.insert_many(datalist).execute()
def handleMessage(tag: Tag, chat: Chat, prev_tag: Tag = None): if not prev_tag: txt = tag.find('div', attrs={'class': 'text'}) reply_to = tag.find('div', attrs={'class': 'reply_to_details'}) fromUser = tag.find('div', attrs={ 'class': 'from_name' }).getText().strip() chat.push( Message( int(tag.get('id').replace('message', '')), chat.extractUserAndBotNameFromMessage(fromUser) if chat.isAViaBotMessage(fromUser) else (fromUser, None), txt.getText().strip() if txt else None, tag.find('div', attrs={ 'class': 'pull_right date details' }).get('title'), int(reply_to.a.get('href')) if reply_to else None)) chat.updateUserRecords(fromUser, int(tag.get('id').replace('message', ''))) else: txt = prev_tag.find('div', attrs={'class': 'text'}) fromUser = prev_tag.find('div', attrs={ 'class': 'from_name' }).getText().strip() chat.push( Message( int(tag.get('id').replace('message', '')), chat.extractUserAndBotNameFromMessage(fromUser) if chat.isAViaBotMessage(fromUser) else (fromUser, None), txt.getText().strip() if txt else None, tag.find('div', attrs={ 'class': 'pull_right date details' }).get('title'))) chat.updateUserRecords(fromUser, int(tag.get('id').replace('message', '')))