def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs): if "!" in str(message_object.text)[0]: command = str(message_object.text).replace("!", "").split(" ") parameters = { "user": command[1:], "author_id": author_id, "message_object": message_object, "thread_id": thread_id, "thread_type": thread_type } command = command[0] try: module = __import__(command) new_command = getattr(module, command) instance = new_command(parameters, client=self) except ModuleNotFoundError: self.send( Message(text="Command not found."), thread_id=thread_id, thread_type=thread_type, ) except Exception as e: self.send( Message(text="Error: " + str(e)), thread_id=thread_id, thread_type=thread_type, )
def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs): self.markAsDelivered(thread_id, message_object.uid) self.markAsRead(thread_id) if author_id != self.uid: messenger = message_object.text if messenger == 'inicio': self.send(Message(text="Comiensa el juego"), thread_id=thread_id, thread_type=thread_type) ai_algo = Negamax(6) tresenraya = TresEnRaya([Human_Player(), AI_Player(ai_algo)]) tresenraya.play() else: print(messenger) traduccion = traducir(messenger, language_translator) print(traduccion) respuesta = mensaje(traduccion, session) print(respuesta) voz(respuesta, service) guardarPregunta(con, messenger, respuesta, traduccion) #self.send(Message(text=respuesta), thread_id=thread_id, thread_type=thread_type) self.sendLocalVoiceClips('output.mp3', Message(text=respuesta), thread_id=thread_id, thread_type=thread_type)
def onMessageUnsent(self, mid: str, author_id: str, **kwargs) -> None: if not self.debug: if author_id == self.uid: return author: User = self.fetchUserInfo(author_id)[author_id] name = author.name self.logger.info(f"Caught unsend by {name}.") message = Message( f"{name} unsent a message.", mentions=[Mention(author_id, length=len(name))], ) id = self.send(message) if mid not in self.messages: return message: Message = deepcopy(self.messages[mid]) message.reply_to_id = id files = Reporter.__message_files(message) if files: self.sendRemoteFiles(files, message) else: self.send(message)
def run(self): seed(randint(0, 100)) mentions = [ Mention(self.author_id, length=len(self.author.first_name) + 1) ] if len(self.user_params) > 0: if self.user_params[0] == "help": response_text = "@" + self.author.first_name response_text += "These are the possible react commands: \n```" for x in self.emoji_dict.keys(): response_text += "\n{}".format(x) response_text += "\n```" self.client.send(Message(text=response_text, mentions=mentions), thread_id=self.thread_id, thread_type=self.thread_type) exit() m = self.message_object reply_id = find_reply_id(m) try: emoji = self.find_reaction_emoji() if emoji != "invalid": self.client.reactToMessage(reply_id, self.find_reaction_emoji()) except FBchatException: response_text = "@{}\nPlease select a message to reply to before reacting.".format( self.author.first_name) self.client.send(Message(text=response_text, mentions=mentions), thread_id=self.thread_id, thread_type=self.thread_type)
def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs): self.markAsDelivered(thread_id, message_object.uid) # self.markAsRead(thread_id) log.info("{} from {} in {}".format(message_object, thread_id, thread_type.name)) # If you're not the author, echo if author_id != self.uid: m = Message() m.text = message_object.text text_msg = "\nthis was sent from a bot cuz Armaan doesn't feel like responding" txt_msg = "".join( list( map( lambda x: x.upper() if random.random() > 0.5 else x.lower(), list(text_msg)))) m.text = txt_msg self.reactToMessage(message_object.uid, MessageReaction.WOW) self.sendRemoteImage( "https://usatftw.files.wordpress.com/2017/05/spongebob.jpg", thread_id=thread_id, thread_type=thread_type) self.send(m, thread_id=thread_id, thread_type=thread_type)
def find_reaction_emoji(self): mentions = [ Mention(self.author_id, length=len(self.author.first_name) + 1) ] if len(self.user_params) == 0: return None elif len(self.user_params) == 1: emoji = self.user_params[0].strip() try: emoji = MessageReaction(emoji) return emoji except ValueError: try: emoji = self.emoji_dict[emoji] if emoji == "run_random": emoji = choose( ["❤", "😍", "😆", "😮", "😢", "😠", "👍", "👎"]) return MessageReaction(emoji) except KeyError: response_text = "@{}\nSorry, you can't react with that.".format( self.author.first_name) self.client.send(Message(text=response_text, mentions=mentions), thread_id=self.thread_id, thread_type=self.thread_type) return "invalid" else: response_text = "@{}\nPlease input only 1 emoji.".format( self.author.first_name) self.client.send(Message(text=response_text, mentions=mentions), thread_id=self.thread_id, thread_type=self.thread_type) return "invalid"
def test_delete_messages(client): text1 = "This message will stay" text2 = "This message will be removed" mid1 = client.send(Message(text=text1)) mid2 = client.send(Message(text=text2)) client.delete_messages(mid2) (message,) = client.fetch_thread_messages(limit=1) assert subset(vars(message), uid=mid1, author=client.uid, text=text1)
def test_t_ms_full(session): """A full example of parsing of data in /t_ms.""" payload = { "deltas": [{ "deltaMessageReaction": { "threadKey": { "threadFbId": 4321 }, "messageId": "mid.$XYZ", "action": 0, "userId": 1234, "reaction": "😢", "senderId": 1234, "offlineThreadingId": "1122334455", } }] } data = { "deltas": [ { "payload": [ord(x) for x in _util.json_minimal(payload)], "class": "ClientPayload", }, { "class": "NoOp", }, { "forceInsert": False, "messageId": "mid.$ABC", "threadKey": { "threadFbId": "4321" }, "class": "ForcedFetch", }, ], "firstDeltaSeqId": 111111, "lastIssuedSeqId": 111113, "queueEntityId": 1234, } thread = Group(session=session, id="4321") assert [ ReactionEvent( author=User(session=session, id="1234"), thread=thread, message=Message(thread=thread, id="mid.$XYZ"), reaction="😢", ), UnfetchedThreadEvent( thread=thread, message=Message(thread=thread, id="mid.$ABC"), ), ] == list(parse_events(session, "/t_ms", data))
def test_message_format_mentions(): expected = ( "Hey 'Peter'! My name is Michael", [ Mention(thread_id="1234", offset=4, length=7), Mention(thread_id="4321", offset=24, length=7), ], ) assert expected == Message.format_mentions( "Hey {!r}! My name is {}", ("1234", "Peter"), ("4321", "Michael") ) assert expected == Message.format_mentions( "Hey {p!r}! My name is {}", ("4321", "Michael"), p=("1234", "Peter") )
def run(self): mentions = [Mention(self.author_id, length=len(self.author.first_name) + 1)] if len(self.user_params) == 0: response_text = "@" + self.author.first_name + " Here you go." + "\n" + "https://en.wikipedia.org/wiki/Nothing" else: try: link = "https://en.wikipedia.org/w/index.php?search="+"_".join(self.user_params) webpage = requests.get(link) text = str(bs4.BeautifulSoup(webpage.text, 'html.parser').find("div", class_="mw-search-result-heading")) if text == "None": link = webpage.url else: text = text[text.find("href") + 6:] text = text[:text.find("\"")] link = "https://en.wikipedia.org" + text response_text = "@" + self.author.first_name + " Here's what I found for you about " + " ".join(self.user_params) \ + "\n" + link except: response_text = "@" + self.author.first_name + " Wikipedia cannot get a result." self.client.send( Message(text=response_text, mentions= mentions), thread_id=self.thread_id, thread_type=self.thread_type )
def test_send_sticker(client, catch_event, compare, sticker): with catch_event("on_message") as x: mid = client.send(Message(sticker=sticker)) assert compare(x, mid=mid) assert subset(vars(x.res["message_object"]), id=mid, author=client.id) assert subset(vars(x.res["message_object"].sticker), id=sticker.id)
def run(self): mentions = [ Mention(self.author_id, length=len(self.author.first_name) + 1) ] response_text = "@" + self.author.first_name + " Here is your link: \n" steal = events() if len(self.user_params) != 0: try: url = steal.shorten_url(self.user_params[0]) response_text += url except: try: url = steal.shorten_url("http://" + self.user_params[0]) response_text += url except: response_text = "@" + self.author.first_name + " Could not find link to shorten" elif self.message_object.replied_to != None: try: url = steal.shorten_url(self.message_object.replied_to.text) response_text += url except: try: url = steal.shorten_url( "http://" + self.message_object.replied_to.text) response_text += url except: response_text = "@" + self.author.first_name + " Could not find link to shorten" else: response_text = "@" + self.author.first_name + " Could not find link to shorten" self.client.send(Message(text=response_text, mentions=mentions), thread_id=self.thread_id, thread_type=self.thread_type)
def run(self): try: response = json.loads( requests.get('http://localhost:4040/api/tunnels').text) pub_url = response['tunnels'][0]['public_url'] except: p = subprocess.Popen("exec " + "~/ngrok tcp 22", stdout=subprocess.PIPE, shell=True) while (True): try: response = json.loads( requests.get('http://localhost:4040/api/tunnels').text) pub_url = response['tunnels'][0]['public_url'] break except: print("Attempting ngrok connection again...") response_text = """ @{}\nPublic URL: {} """.format(self.author.first_name, pub_url) mentions = [ Mention(self.author_id, length=len(self.author.first_name) + 1) ] self.client.send(Message(text=response_text, mentions=mentions), thread_id=self.thread_id, thread_type=self.thread_type)
def reply(text_message, client, thread_id): if client.uid == thread_id: return mess = Message(text=text_message) client.send(mess, thread_id=thread_id, thread_type=ThreadType.USER) client.delay()
def get_message_by_id(self, chat: Chat, msg_id: MessageID) -> Optional['Message']: index = None if msg_id.split('.')[-1].isdecimal(): # is sub-message index = int(msg_id.split('.')[-1]) msg_id = MessageID('.'.join(msg_id.split('.')[:-1])) thread_id, thread_type = self.client._getThread(chat.uid, None) message_info = self.client._forcedFetch(thread_id, msg_id).get("message") message = Message._from_graphql(message_info) efb_msg = self.client.build_efb_msg(msg_id, chat.uid, message.author, message) attachments = message_info.get('delta', {}).get('attachments', []) if attachments: attachment = attachments[index] self.client.attach_media(efb_msg, attachment) efb_msg.uid = msg_id return efb_msg
def run(self): if 'countdown' not in self.database: self.database['countdown'] = "on" mentions = [Mention(self.author_id, length=len(self.author.first_name) + 1)] if len(self.user_params) == 0: response_text = "@" + self.author.first_name + " Countdown is currently " + self.database['countdown'] elif self.user_params[0].lower() == "off": self.database['countdown'] = "off" response_text = "@" + self.author.first_name + " Countdown is now " + self.database['countdown'] elif self.user_params[0].lower() == "on": self.database['countdown'] = "on" response_text = "@" + self.author.first_name + " Countdown is now " + self.database['countdown'] elif len(self.user_params) == 1 and self.database['countdown'] == "on": try: count = int(self.user_params[0]) if count > 10: response_text = "I'm too lazy to do that..." elif count <= 0: response_text = "Lets do it again!" else: response_text = "!countdown " + str(count - 1) mentions = None except ValueError: response_text = "You think you're soooo clever? Not anymore " + self.author.first_name + ", because I now have error catching!" mentions = None else: response_text = "Sorry, !countdown is currently disabled. Please type !countdown ON and try again." mentions = None self.client.send( Message(text=response_text, mentions=mentions), thread_id=self.thread_id, thread_type=self.thread_type )
def catch_event(client2): t = ClientThread(client2) t.start() @contextmanager def inner(method_name): caught = CaughtValue() old_method = getattr(client2, method_name) # Will be called by the other thread def catch_value(*args, **kwargs): old_method(*args, **kwargs) # Make sure the `set` is only called once if not caught.is_set(): caught.set(kwargs) setattr(client2, method_name, catch_value) yield caught caught.wait() if not caught.is_set(): raise ValueError("The value could not be caught") setattr(client2, method_name, old_method) yield inner t.should_stop.set() try: # Make the client send a messages to itself, so the blocking pull request will return # This is probably not safe, since the client is making two requests simultaneously client2.send(Message(text=random_hex()), client2.uid) finally: t.join()
async def main(): await client.start("<email>", "<password>") print(f"Own ID: {client.uid}") await client.send(Message(text="Hi me!"), thread_id=client.uid, thread_type=ThreadType.USER) await client.logout()
def yt(self, author_id, message_object, thread_id, thread_type, arguments, admin, **kwargs): youtube_link = "https://www.youtube.com/results?search_query=" suffix = "" for x in arguments: suffix += "+"+x suffix = suffix[1:] url = quote_plus(youtube_link+suffix,"/:+?=") print(url) req = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) page = urlopen(req) soup = BeautifulSoup(page, 'html.parser') youtube_vids = soup.findAll('a') first = True c = 0 youtube_videos = [] for i in youtube_vids: # super inefficient but I'm lazy if (i.get("href")[:9] == "/watch?v="): if c == 0: first_video = "https://www.youtube.com"+i.get("href") else: youtube_videos.append("https://www.youtube.com"+i.get("href")) c += 1 c = 0 youtube_videos = list(set(youtube_videos)) for i in youtube_videos: if c == 0: youtube_vid_message = "First Result:\n\n"+first_video+"\n\nMore Results:\n\n"+i+"\n\n" elif c < 5: youtube_vid_message += i+"\n\n" c += 1 client.setTypingStatus(TypingStatus.TYPING, thread_id=thread_id, thread_type=thread_type) self.send(Message(text=youtube_vid_message), thread_id=thread_id, thread_type=thread_type)
def send_message(self): """ args: { 'text': text of message, 'mentions': list of Mention objects (=None if none) } """ if 'mentions' in self.args: (self.client).send(Message(text=self.args['text'], mentions=self.args['mentions']), thread_id=self.thread_id, thread_type=self.thread_type) else: (self.client).send(Message(text=self.args['text'], mentions=None), thread_id=self.thread_id, thread_type=self.thread_type)
def run(self): response_text = None if len(self.user_params) == 0: response_text = "@" + self.author.first_name + " Please enter something. Anything." else: try: if len(self.user_params) == 1: response_text = "@" + self.author.first_name + " Your lucky number is {}"\ .format(random.randint(1, int(self.user_params[0]))) elif len(self.user_params) == 2 and int( self.user_params[1]) > int(self.user_params[0]): response_text = "@" + self.author.first_name + " Your lucky number is {}"\ .format(random.randint(int(self.user_params[0]), int(self.user_params[1]))) except: pass if response_text is None: response_text = "@" + self.author.first_name + " Your lucky item is " + random.choice( self.user_params) mentions = [ Mention(self.author_id, length=len(self.author.first_name) + 1) ] self.client.send(Message(text=response_text, mentions=mentions), thread_id=self.thread_id, thread_type=self.thread_type)
async def main(): client = Client() start = await client.start(conf.bot_user, conf.bot_password) logging.info('Printing {} to {}'.format(message, who)) await client.send(Message(text=message), thread_id=thread_id, thread_type=thread_type)
def run(self): mentions = [ Mention(self.author_id, length=len(self.author.first_name) + 1) ] response_text = "@" + self.author.first_name + " " if len(self.user_params) > 0: text = " ".join(self.user_params) DIALOGFLOW_PROJECT_ID = 'dentaku-fyaltw' DIALOGFLOW_LANGUAGE_CODE = 'en-US' os.environ[ "GOOGLE_APPLICATION_CREDENTIALS"] = 'dentaku-dialogflow.json' SESSION_ID = self.thread_id session_client = dialogflow.SessionsClient() session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID) text_input = dialogflow.types.TextInput( text=text, language_code=DIALOGFLOW_LANGUAGE_CODE) query_input = dialogflow.types.QueryInput(text=text_input) response = session_client.detect_intent(session=session, query_input=query_input) response_text += response.query_result.fulfillment_text else: response_text += "Please say something" self.client.send(Message(text=response_text, mentions=mentions), thread_id=self.thread_id, thread_type=self.thread_type)
def run(self): try: link = "https://www.theweathernetwork.com/ca/search?q=" for i in self.user_params: if i == "-t": break else: link += i + "%20" webpage = requests.get(link) text = str( bs4.BeautifulSoup(webpage.text, 'html.parser').find("li", class_="result")) h = text.find("href") e = text[h:].find(">") r = text[h:h + e] link = "https://www.theweathernetwork.com" + r[6:-1] response_text = "@" + self.author.first_name + " Check for yourself at " + link except: response_text = "@" + self.author.first_name + " Dude is that even a place." mentions = [ Mention(self.author_id, length=len(self.author.first_name) + 1) ] self.client.send(Message(text=response_text, mentions=mentions), thread_id=self.thread_id, thread_type=self.thread_type)
def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs): self.markAsDelivered(thread_id, message_object.uid) #self.markAsRead(thread_id) text = message_object.text if text == "": return if (author_id != self.uid) or self.Debug: if author_id in self.idName: name = self.idName[author_id] else: page = requests.get('https://www.facebook.com/' + author_id, cookies=self.session) name = BeautifulSoup(page.text, "lxml").title.string self.idName[author_id] = name try: self.msglist.insert(END, name + ": " + text) except Exception as ex: self.msglist.insert(END, name + ": 訊息包含不支援之符號") say(text, name) if author_id != self.uid or text != "Auto reply: " + DNDStr: if DNDStatus.get() and thread_type is not ThreadType.GROUP: self.send(Message(text="Auto reply: " + DNDStr), thread_id=thread_id, thread_type=thread_type) self.msglist.data.append( [thread_id, thread_type, name, message_object.text]) self.msglist.yview(END) else: if (message_object.text == 'Logout'): self.logout() print("logged out")
def pranshu_comment(client, author_id, message_object, thread_id, thread_type): client.send(Message( text= "Pranshu is a student at the University of Illinois Urbana-Champaign studying Computer Science and Statistics. My interests lie in High Performance Computing (HPC) and in AI/Deep Learning. Recently I attended the Super Computing 19 conference where I represented my school as a member of the University of Illinois Student Cluster Competition team; our team won 2nd place nationwide. I've recently also won 2nd place at the National Center for Supercomputing Applications Deep Learning Hackathon. At the Technology Student Association’s national conference in June, 2019, my team won 1st place out of over 75 teams in a research presentation competition on exploring a novel application of artificial intelligence in a domain field (website: pinkai.tech). I am an enthusiastic candidate for any role relating to HPC or Deep Learning; I hope to expand my skill set in the summer of 2020 through an internship at a company focusing on these disciplines. " ), thread_id=thread_id, thread_type=thread_type)
def run(self): service = build('calendar', 'v3', credentials=self.get_credentials()) # Call the Calendar API now = datetime.datetime.utcnow().isoformat( ) + 'Z' # 'Z' indicates UTC time events_result = service.events().list(calendarId='primary', timeMin=now, maxResults=3, singleEvents=True, orderBy='startTime').execute() events = events_result.get('items', []) event_list = "*All upcoming events:*\n" if not events: event_list = "No upcoming events found." for event in events: start = event['start'].get('dateTime', event['start'].get('date')) event_list += event['summary'] + "\n" + dateutil.parser.parse( start).strftime( "%A, %b %-d at %-I:%M%p") + "\n" + self.shorten_url( event['htmlLink']) + "\n\n" response_text = "@" + self.author.first_name + "\n" + event_list mentions = [ Mention(self.author_id, length=len(self.author.first_name) + 1) ] self.client.send(Message(text=response_text, mentions=mentions), thread_id=self.thread_id, thread_type=self.thread_type)
def send_msg(name, opened): message = name + " has " if opened: message += "opened the door." else: message += "unsuccessfully tried to open the door." fb_client.send(Message(text=message), thread_id=recip_id)
def run(self): response_text = "@{}".format(self.author.first_name) if len(self.user_params) == 0: # sends general information about all commands for x in modules: instance = self.get_instance(x) response_text += "\n\n!" + x + ": " + instance.documentation[ "function"] response_text += "\n\nIf you want to learn more about a specific command, send '!help !COMMAND_NAME'." elif len(self.user_params) == 1: # sends detailed information about a specific command c_name = str(self.user_params[0]).replace("!", "", 1) if c_name in modules: instance = self.get_instance(c_name) response_text += """ \nThe !{} command: \nFunction: {} \nParameters: {} """.format(c_name, instance.documentation["function"], instance.documentation["parameters"]) else: response_text += "\nlol good try" else: response_text += "\nSorry, we can only provide information on one command at a time!" \ + "\nPlease use the format: '!help !COMMAND_NAME'" mentions = [ Mention(self.author_id, length=len(self.author.first_name) + 1) ] self.client.send(Message(text=response_text, mentions=mentions), thread_id=self.thread_id, thread_type=self.thread_type)
def sendReply(): #Handle replying log.info("Sending message to " + sender_name + ", text:" + reply) #Send the message self.send(Message(text=reply), thread_id=thread_id, thread_type=thread_type)