def message_with_mentions(request, client, client2, group): text = "Hi there [" mentions = [] if "me" in request.param: mentions.append(Mention(thread_id=client.uid, offset=len(text), length=2)) text += "me, " if "other" in request.param: mentions.append(Mention(thread_id=client2.uid, offset=len(text), length=5)) text += "other, " # Unused, because Facebook don't properly support sending mentions with groups as targets if "group" in request.param: mentions.append(Mention(thread_id=group["id"], offset=len(text), length=5)) text += "group, " text += "nothing]" return Message(text, mentions=mentions)
def test_fetch_message_mentions(client): text = "This is a test of fetchThreadMessages" mentions = [Mention(client.uid, offset=10, length=4)] mid = client.send(Message(text, mentions=mentions)) message, = client.fetchThreadMessages(limit=1) assert subset(vars(message), uid=mid, author=client.uid, text=text) for i, m in enumerate(mentions): assert vars(message.mentions[i]) == vars(m)
def two_iq(client, t_id, t_type): '''sends "Did you mean Lukas" and tags him''' client.send( Message(text="Did you mean @Lukas Miezys? Opaaaaaaaaaaaaaaaaaaaaa", mentions=[Mention('100000491391008', offset=13, length=13)]), thread_id=t_id, thread_type=t_type, ) return
def bmw(client, t_id, t_type): '''sends Want to see Tomas... + wojak with bmw car''' client.sendLocalImage( "photos/tomas_wojak_bmw.png", Message( text="Want to see @Tomas Kučejevas in his 40s with his car????", mentions=[Mention('100001826192111', offset=12, length=16)]), thread_id=t_id, thread_type=t_type, ) return
def polish(client, t_id, t_type): '''sends "Did you mean Rafal... + tags him + some polska words''' client.send( Message( text="Did you mean @Rafal Michalkiewicz? Kurwa polski lewandowski", mentions=[Mention('100000494913408', offset=13, length=20)]), thread_id=t_id, thread_type=t_type, ) return
def alarm(self, alarm: Alarm): msg = ("ALARM!\n" "Adres: {}\n" "Rodzaj: {}\n" "Opis: {}\n" "Dysponowano: {}\n".format( alarm.address, alarm.sub_kind, alarm.description, alarm.dispatched_bsis_name, )) if self.client: group = self.client.fetchGroupInfo(FB_GROUP_ID)[FB_GROUP_ID] mentions = [ Mention(uid, offset=0, length=6) for uid in group.participants ] message = Message(text=msg, mentions=mentions) if alarm.latitude and alarm.longitude: self.client.sendLocation(LocationAttachment( alarm.latitude, alarm.longitude), message=message) else: self.client.send(message) if self.wh_url: msg += "\n@everyone" data = {"content": msg} requests.post(self.wh_url, json=data) if self.nexmo: ncco = [{ "action": "talk", "voiceName": "Jacek", "text": f"{alarm.address or ''}, {alarm.sub_kind or ''}, {alarm.description or ''}", }] self.nexmo.create_call({ "to": [{ "type": "phone", "number": number } for number in NEXMO_NUMBERS], "from": { "type": "phone", "number": NEXMO_APP_NUMBER }, "ncco": ncco, })
def send_google_photos_to_fb(client, keywords, author_id, threadid, threadtype): '''sends photos from directory to facebook's thread, tags the author and also specifies what subreddit is used''' code_dir = os.getcwd() + '/downloaded_photos/google/' google_photos_dir = code_dir + keywords google_photos = os.listdir(google_photos_dir) #if we have atleast one photo if len(google_photos) > 0: author_name = systemfiles.utility.get_name(client, author_id) #first what we did client.send( Message(text='Photos googled by: ' + author_name + ', ' + str(len(google_photos)) + ' by keyword ' + keywords + ' shown below:', mentions=[ Mention(author_id, offset=19, length=len(author_name)) ]), thread_id=threadid, thread_type=threadtype, ) #send all photos for photo in google_photos: client.sendLocalImage( google_photos_dir + '/' + photo, thread_id=threadid, thread_type=threadtype, ) return #if we have less than 1 photo else: #no photos was used client.send( Message(text='No photos found by keywords: ' + keywords), thread_id=threadid, thread_type=threadtype, ) return '''possible arguments for image-download
def test_send_mentions(client, client2, thread, catch_event, compare): text = "Hi there @me, @other and @thread" mentions = [ dict(thread_id=client.uid, offset=9, length=3), dict(thread_id=client2.uid, offset=14, length=6), dict(thread_id=thread["id"], offset=26, length=7), ] with catch_event("onMessage") as x: mid = client.send( Message(text, mentions=[Mention(**d) for d in mentions])) assert compare(x, mid=mid, message=text) assert subset(vars(x.res["message_object"]), uid=mid, author=client.uid, text=text) # The mentions are not ordered by offset for m in x.res["message_object"].mentions: assert vars(m) in mentions
def matrix_to_facebook(content: TextMessageEventContent, room_id: RoomID) -> Message: mentions = [] reply_to_id = None if content.relates_to.rel_type == RelationType.REFERENCE: message = DBMessage.get_by_mxid(content.relates_to.event_id, room_id) if message: content.trim_reply_fallback() reply_to_id = message.fbid if content.format == Format.HTML and content.formatted_body: parsed = MatrixParser.parse(content.formatted_body) text = parsed.text mentions = [ Mention(thread_id=mention.extra_info['fbid'], offset=mention.offset, length=mention.length) for mention in parsed.entities ] else: text = content.body return Message(text=text, mentions=mentions, reply_to_id=reply_to_id)
def send_reddit_photos(client, subreddit, author_id, threadid, threadtype): '''sends photos from directory to facebook's thread, tags the author and also specifies what subreddit is used''' code_dir = os.getcwd() + '/downloaded_photos/reddit/' reddit_photos_dir = code_dir + subreddit reddit_photos = os.listdir(reddit_photos_dir) #if we have atleast one photo if len(reddit_photos) > 0: author_name = systemfiles.utility.get_name(client, author_id) #first what we did client.send( Message(text='Photos asked by: ' + author_name + ', ' + str(len(reddit_photos)) + ' photos from [r/' + subreddit + '] below:', mentions=[Mention(author_id, offset=17, length=len(author_name))]), thread_id=threadid, thread_type=threadtype, ) #send all photos for photo in reddit_photos: client.sendLocalImage( reddit_photos_dir + '/' + photo, thread_id=threadid, thread_type=threadtype, ) return #if we have less than 1 photo else: #no photos was used client.send( Message(text='No photos downloaded from [r/' + subreddit + ']'), thread_id=threadid, thread_type=threadtype, ) return
def _extract_mentions(self, message_text): """ Takes message in raw text form and returns a list of appropriate Mentions objects Args: message_text: message in raw text form Returns: A list of :class:`fbchat.models.Mention` objects """ # Find all occurrences of @ (for offset) index = 0 mention = [] at_indices = [] for c in message_text: if c is '@': at_indices.append(index) index += 1 # used for offset at_count = 0 elements = message_text.split(" ") for element in elements: # look for @s if element.startswith("@"): users = self.searchForUsers(element[1:]) # @ is a valid Mention if len(users) is not 0: user = users[0] mention.append( \ Mention(user.uid, offset=at_indices[at_count], \ length=len(element))) at_count += 1 return (None if len(mention) is 0 else mention)
def send_message(self, msg: EFBMessage) -> Message: self.logger.debug("Received message from master: %s", msg) try: target_msg_offset = 0 prefix = "" mentions = [] # Send message reaction # if msg.target and msg.text.startswith('r`') and \ # msg.target.uid.startswith("mid.$"): # self.logger.debug("[%s] Message is a reaction to another message: %s", msg.uid, msg.text) # msg_id = ".".join(msg.target.uid.split(".", 2)[:2]) # if getattr(MessageReaction, msg.text[2:], None): # self.client.reactToMessage(msg_id, getattr(MessageReaction, msg.text[2:])) # else: # self.client.reactToMessage(msg_id, self.CustomReaction(msg.text[2:])) # msg.uid = "__reaction__" # return msg # Message substitutions if msg.substitutions: self.logger.debug("[%s] Message has substitutions: %s", msg.uid, msg.substitutions) for i in msg.substitutions: mentions.append(Mention(msg.substitutions[i].id, target_msg_offset + i[0], i[1] - i[0])) self.logger.debug("[%s] Translated to mentions: %s", msg.uid, mentions) fb_msg = Message(text=prefix + msg.text, mentions=mentions) thread: Thread = self.client.fetchThreadInfo(msg.chat.uid)[str(msg.chat.uid)] if msg.target and msg.target.uid: fb_msg.reply_to_id = msg.target.uid if msg.type in (MsgType.Text, MsgType.Unsupported): # Remove variation selector-16 (force colored emoji) for # matching. emoji_compare = msg.text.replace("\uFE0F", "") if emoji_compare == "👍": fb_msg.sticker = Sticker(uid=EmojiSize.SMALL.value) if not prefix: fb_msg.text = None elif emoji_compare[:-1] == "👍" and emoji_compare[-1] in 'SML': if emoji_compare[-1] == 'S': fb_msg.sticker = Sticker(uid=EmojiSize.SMALL.value) elif emoji_compare[-1] == 'M': fb_msg.sticker = Sticker(uid=EmojiSize.MEDIUM.value) elif emoji_compare[-1] == 'L': fb_msg.sticker = Sticker(uid=EmojiSize.LARGE.value) if not prefix: fb_msg.text = None elif emoji_compare[:-1] in emoji.UNICODE_EMOJI and emoji_compare[-1] in 'SML': # type: ignore self.logger.debug("[%s] Message is an Emoji message: %s", msg.uid, emoji_compare) if emoji_compare[-1] == 'S': fb_msg.emoji_size = EmojiSize.SMALL elif emoji_compare[-1] == 'M': fb_msg.emoji_size = EmojiSize.MEDIUM elif emoji_compare[-1] == 'L': fb_msg.emoji_size = EmojiSize.LARGE fb_msg.text = emoji_compare[:-1] msg.uid = self.client.send(fb_msg, thread_id=thread.uid, thread_type=thread.type) elif msg.type in (MsgType.Image, MsgType.Sticker, MsgType.Animation): msg_uid = self.client.send_image_file(msg.filename, msg.file, msg.mime, message=fb_msg, thread_id=thread.uid, thread_type=thread.type) if msg_uid.startswith('mid.$'): self.client.sent_messages.add(msg_uid) self.logger.debug("Sent message with ID %s", msg_uid) msg.uid = msg_uid elif msg.type == MsgType.Voice: files = self.upload_file(msg, voice_clip=True) msg_uid = self.client._sendFiles(files=files, message=fb_msg, thread_id=thread.uid, thread_type=thread.type) if msg_uid.startswith('mid.$'): self.client.sent_messages.add(msg_uid) self.logger.debug("Sent message with ID %s", msg_uid) msg.uid = msg_uid elif msg.type in (MsgType.File, MsgType.Video): files = self.upload_file(msg) msg_uid = self.client._sendFiles(files=files, message=fb_msg, thread_id=thread.uid, thread_type=thread.type) if msg_uid.startswith('mid.$'): self.client.sent_messages.add(msg_uid) self.logger.debug("Sent message with ID %s", msg_uid) msg.uid = msg_uid elif msg.type == MsgType.Status: assert (isinstance(msg.attributes, StatusAttribute)) status: StatusAttribute = msg.attributes if status.status_type in (StatusAttribute.Types.TYPING, StatusAttribute.Types.UPLOADING_VOICE, StatusAttribute.Types.UPLOADING_VIDEO, StatusAttribute.Types.UPLOADING_IMAGE, StatusAttribute.Types.UPLOADING_FILE): self.client.setTypingStatus(TypingStatus.TYPING, thread_id=thread.uid, thread_type=thread.type) threading.Timer(status.timeout / 1000, self.stop_typing, args=(thread.uid, thread.type)).start() elif msg.type == MsgType.Link: assert (isinstance(msg.attributes, LinkAttribute)) link: LinkAttribute = msg.attributes if self.flag('send_link_with_description'): info: Tuple[str, ...] = (link.title,) if link.description: info += (link.description,) info += (link.url,) text = "\n".join(info) else: text = link.url if fb_msg.text: text = fb_msg.text + "\n" + text fb_msg.text = text msg.uid = self.client.send(fb_msg, thread_id=thread.uid, thread_type=thread.type) elif msg.type == MsgType.Location: assert (isinstance(msg.attributes, LocationAttribute)) location_attr: LocationAttribute = msg.attributes location = LocationAttachment(latitude=location_attr.latitude, longitude=location_attr.longitude) self.client.sendPinnedLocation(location, fb_msg, thread_id=thread.uid, thread_type=thread.type) else: raise EFBMessageTypeNotSupported() return msg finally: if msg.file and not msg.file.closed: msg.file.close() self.client.markAsSeen() self.client.markAsRead(msg.chat.uid)