def test_default_thread(client1, thread):
    client1.setDefaultThread(thread["id"], thread["type"])
    assert client1.send(Message(text="Sent to the specified thread"))

    client1.resetDefaultThread()
    with pytest.raises(ValueError):
        client1.send(Message(text="Should not be sent"))
def main(json_input, context):

    fbClient = Client(FB_USER, FB_PASSWORD)
    fbUsers = fbClient.fetchAllUsers()
    fbUsersList = [user.uid for user in fbUsers if user.uid != "0"]

    # Getting weather information
    forecastPayload = {
        "apikey": ACCUWEATHER_KEY,
        "details": True,
        "metric": True
    }

    alertPayload = {"apikey": ACCUWEATHER_KEY}

    r = requests.get(ACCUWEATHER_FORECAST_URL, params=forecastPayload)
    weatherForecast = r.json()

    r = requests.get(ACCUWEATHER_ALARM_URL, params=alertPayload)
    weatherAlerts = r.json()

    dailyMinimum = weatherForecast["DailyForecasts"][0]["Temperature"][
        "Minimum"]["Value"]
    dailyMaximum = weatherForecast["DailyForecasts"][0]["Temperature"][
        "Maximum"]["Value"]
    feelsLikeMinimum = weatherForecast["DailyForecasts"][0][
        "RealFeelTemperature"]["Minimum"]["Value"]
    feelsLikeMaximum = weatherForecast["DailyForecasts"][0][
        "RealFeelTemperature"]["Maximum"]["Value"]
    weatherSummary = weatherForecast["DailyForecasts"][0]["Day"][
        "LongPhrase"].lower()

    alerts = []

    if len(weatherAlerts) > 0:
        for alert in weatherAlerts[0]["Alarms"]:
            alertType = alert["AlarmType"]
            alertText = getAlertText(alertType)
            alerts.append(alertText)

    forecastMessage = Message(
        text="Good morning!\nToday's weather calls for " + weatherSummary +
        ".\n\nHigh: " + str(dailyMaximum) + u"°\n(feels like " +
        str(feelsLikeMaximum) + u"°)" + "\nLow: " + str(dailyMinimum) +
        u"°\n(feels like " + str(feelsLikeMinimum) + u"°)")

    # Sending weather updates
    for id in fbUsersList:
        fbClient.send(forecastMessage, thread_id=id)

        for alertText in alerts:
            alertMessage = Message(text=alertText)
            fbClient.send(alertMessage, thread_id=id)

        time.sleep(5)  # sleep for 5 seconds to avoid being too spammy

    fbClient.logout()
Exemple #3
0
 def send_message(self, msg):
     for user_id in self.users_id:
         self.client.send(Message(text=msg),
                          thread_id=user_id,
                          thread_type=ThreadType.USER)
     for group_id in self.groups_id:
         self.client.send(Message(text=msg),
                          thread_id=group_id,
                          thread_type=ThreadType.GROUP)
Exemple #4
0
 def send_image(self, image_path, caption=""):
     for user_id in self.users_id:
         self.client.sendLocalImage(
             image_path,
             message=Message(text=caption),
             thread_id=user_id,
             thread_type=ThreadType.USER,
         )
     for group_id in self.groups_id:
         self.client.sendLocalImage(
             image_path,
             message=Message(text=caption),
             thread_id=group_id,
             thread_type=ThreadType.GROUP,
         )
Exemple #5
0
def main():
    messages = client.fetchThreadMessages(os.environ['THREAD_ID'], limit=200)
    messages.reverse()
    thread = client.fetchThreadInfo(
        os.environ['THREAD_ID'])[os.environ['THREAD_ID']]
    members = [
        member.name for member in client.fetchAllUsersFromThreads([thread])
    ]

    # get times and filter
    release_time, end_time = get_times()
    messages = filter(
        lambda x: int(x.timestamp[:10]) > release_time and int(
            x.timestamp[:10]) < end_time, messages)
    uid_to_time = {}
    for message in messages:
        parsed_time = parse_message(message.text)
        if parsed_time:
            uid_to_time[message.author] = parsed_time
    participants = list(
        client.fetchUserInfo(*list(uid_to_time.keys())).values())
    add_new_users(participants)
    output = build_output(uid_to_time, participants, members)
    print(output)
    if '--send' in sys.argv:
        client.send(Message(text=output),
                    thread_id=os.environ['SEND_THREAD_ID'],
                    thread_type=ThreadType.GROUP)
    if '--commit' in sys.argv:
        session.commit()
Exemple #6
0
def send_message(friend_uid: int = None):

    # Connect to FB client
    client = Client(email=os.environ['EMAIL_ADDRESS'],
                    password=getpass.getpass(prompt='Password: '******'s uid
        persons = client.searchForUsers(
            input('What is the name of your friend: '))

        # Find friend's uid in list of persons
        for person in persons:
            if person.is_friend:
                friend_uid = person.uid
                break

    # Send message
    msg = 'Hejsa din klump'
    for i in range(3):
        client.send(message=Message(text=msg), thread_id=str(friend_uid))
        time.sleep(3)

    print('FB message sent')

    return True
Exemple #7
0
    async def onMessage(self,
                        mid: str = None,
                        author_id: str = None,
                        message: str = None,
                        message_object: Message = None,
                        thread_id: str = None,
                        thread_type: ThreadType = ThreadType.USER,
                        ts: int = None,
                        metadata: Any = None,
                        msg: Any = None) -> None:
        """
        Called when the client is listening, and somebody sends a message

        :param mid: The message ID
        :param author_id: The ID of the author
        :param message: (deprecated. Use `message_object.text` instead)
        :param message_object: The message (As a `Message` object)
        :param thread_id: Thread ID that the message was sent to. See :ref:`intro_threads`
        :param thread_type: Type of thread that the message was sent to. See :ref:`intro_threads`
        :param ts: The timestamp of the message
        :param metadata: Extra metadata about the message
        :param msg: A full set of the data recieved
        :type message_object: models.Message
        :type thread_type: models.ThreadType
        """
        self.log.debug(
            f"onMessage({message_object}, {thread_id}, {thread_type})")
        fb_receiver = self.uid if thread_type == ThreadType.USER else None
        portal = po.Portal.get_by_fbid(thread_id, fb_receiver, thread_type)
        puppet = pu.Puppet.get_by_fbid(author_id)
        if not puppet.name:
            await puppet.update_info(self)
        message_object.uid = mid
        await portal.handle_facebook_message(self, puppet, message_object)
Exemple #8
0
def group_stats(self,
                thread_id,
                thread_type,
                time_string='1 day',
                verbose=False):
    homies = dict(data.get_homie_list())
    homie_results = []
    string = "Hydration Stats over the past {}:".format(time_string)
    for hid in homies:
        stats = homie_stats(hid, time_string)
        homie_results.append([homies[hid], stats[0], stats[1]])

    homie_results.sort(key=lambda x: (x[1]), reverse=True)
    homie_results = filter(lambda x: x[0] != 'AssumeZero Bot', homie_results)
    king_quota = 1
    for h in homie_results:
        if verbose:
            string = string + "\n - {} drank {}L (finishing {} bottles total in the past {})".format(
                h[0], h[1], h[2], time_string)
        else:
            if h[1] < 2.0:
                string = string + "\n 🥵 "
            elif king_quota > 0:
                string = string + "\n 👑 "
                king_quota = 0
            else:
                string = string + "\n 👍 "
            string = string + "{}: {}L".format(h[0], h[1])
    self.send(Message(text=string),
              thread_id=thread_id,
              thread_type=thread_type)
Exemple #9
0
def test_send_sticker(client, catch_event, compare, sticker):
    with catch_event("onMessage") as x:
        mid = client.send(Message(sticker=sticker))

    assert compare(x, mid=mid)
    assert subset(vars(x.res["message_object"]), uid=mid, author=client.uid)
    assert subset(vars(x.res["message_object"].sticker), uid=sticker.uid)
Exemple #10
0
def listen(fbClient):
    r = requests.get('http://localhost:4242/api/messages')
    while True:
        r = requests.get('http://localhost:4242/api/stream', stream=True)
        for msg in r.iter_lines():
            if msg:
                print(msg)
                jmsg = json.loads(msg)
                if jmsg["gateway"] == "":
                    continue

                if jmsg["gateway"] == "FBgateway":
                    sendMsg(
                        "bot", "FBgateway",
                        "This gateway is linked to every thread on facebook and can't be used for sending messages."
                    )
                else:
                    fbThread = revThreads[jmsg["gateway"]]
                    if len(fbThread) > 10:
                        threadType = ThreadType.GROUP
                    else:
                        threadType = ThreadType.USER

                    fbClient.send(Message(text=jmsg["text"]),
                                  thread_id=fbThread,
                                  thread_type=threadType)
    r.Close()
Exemple #11
0
def getRunners(self, thread_id, thread_type):
    runners_list = data.get_runners_list()
    self.all_runners = dict(runners_list)
    print(self.all_runners)
    self.send(Message(text='Refreshed runners list.'),
              thread_id=thread_id,
              thread_type=thread_type)
Exemple #12
0
def runningChadCheck(self, thread_id, thread_type, athlete, athleteName):
    rexStats = getStats(self.all_runners[self.current_running_chad])
    larryStats = getStats(athlete)
    larryScore = 0
    response = 'I f****d up somehow, whoops'
    if (int(larryStats[1].replace(',', '')) > int(rexStats[1].replace(',',
                                                                      ''))):
        larryScore = larryScore + 1
    if float(larryStats[0].replace(',', '')) > float(rexStats[0].replace(
            ',', '')):
        larryScore = larryScore + 1
    if (int(larryStats[3].replace(',', '')) > int(rexStats[3].replace(',',
                                                                      ''))):
        larryScore = larryScore + 1
    if larryScore == 3:
        response = 'Yes, {} is currently ahead in {}/3 categories.'.format(
            athleteName, larryScore)
    else:
        response = 'Not yet, {} is currently ahead in {}/3 categories.'.format(
            athleteName, larryScore)
    if athleteName == self.current_running_chad:
        response = '{} is the current running chad.'.format(athleteName)

    self.send(Message(text=response),
              thread_id=thread_id,
              thread_type=thread_type)
Exemple #13
0
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
Exemple #14
0
def test_send_images(client, catch_event, compare, method_name, url):
    text = "An image sent with {}".format(method_name)
    with catch_event("onMessage") as x:
        mid = getattr(client, method_name)(url, Message(text))

    assert compare(x, mid=mid, message=text)
    assert subset(vars(x.res["message_object"]), uid=mid, author=client.uid, text=text)
    assert x.res["message_object"].attachments[0]
Exemple #15
0
 def send_local_file_with_message(self, thread_id: str, file_path: str,
                                  message: str) -> None:
     """ Sends an file with a message to specified thread """
     self.client.sendLocalFiles(
         file_path,
         message=Message(text=message),
         thread_id=thread_id,
         thread_type=ThreadType.GROUP,
     )
Exemple #16
0
 def onMessage(self, message_object, thread_id, **kwargs):
     if self.rooms == None:
         self.get_rooms()
     if thread_id not in self.rooms:
         chat.log('4')
         t = self.fetchThreadInfo(thread_id)
         for k, v in t.items:
             self.rooms[k] = Room(self, v)
     self.rooms[thread_id].add_message(Message(message_object))
Exemple #17
0
def onMessage(group, message):
    if group in tells:
        a = message.author
        t = tells[group]
        if a in t:
            for m in t[a]:
                group.send(Message(text=str(m)))
            del t[a]
            group.store(str(a), [])
Exemple #18
0
 def send_remote_image_with_message(self, thread_id: str, image_url: str,
                                    message: str) -> None:
     """ Sends an image with a message to specified thread """
     self.client.sendRemoteImage(
         image_url,
         message=Message(text=message),
         thread_id=thread_id,
         thread_type=ThreadType.GROUP,
     )
Exemple #19
0
    def onMessage(self, author_id, message_object, thread_id, thread_type,
                  **kwargs):
        matchList = self.MainRegex.findall(message_object.text)
        # Have I been called? if not, do nothing.
        if 'mtgbot:' in message_object.text:
            return
        if len(matchList) != 0:
            for name in matchList:
                if name.lower() == 'luke':
                    alteredName = self.LukesCards.getNextCard()
                else:
                    alteredName = utils.nicknames(name)
                if alteredName != name:
                    # A nickname has been found, jump straight to scryfall
                    cardData = services.scryfall(alteredName)
                else:
                    cardData = services.cardFetch(alteredName)

                if cardData:
                    # if cardData exists, the best match was found! fire away!
                    # obviously, no gurantee it will be the card you wanted!
                    if cardData['dualfaced']:
                        #check in file cache
                        filename = services.buildDualFaced(cardData)
                        self.sendLocalImage(
                            './cache/{}'.format(filename),
                            message=Message(
                                text='mtgbot: {}'.format(cardData['name'])),
                            thread_id=thread_id,
                            thread_type=thread_type)

                    else:
                        print('sending remote image')
                        self.sendRemoteImage(
                            cardData['imageurls'][0],
                            message=Message(
                                text='mtgbot: {}'.format(cardData['name'])),
                            thread_id=thread_id,
                            thread_type=thread_type)
                else:
                    self.send(message=Message(
                        text='mtgbot: No card found for {}'.format(name)),
                              thread_id=thread_id,
                              thread_type=thread_type)
Exemple #20
0
def fb_mess_bot(client, language):
    users = client.fetchThreadList()
    if language == "English":
        print(f"Users you most recently talked to: {users}")
    else:
        print(f"Utenti con cui hai parlato di più recentemente: {users}")
    detailed_users = [list(client.fetchThreadInfo(user.uid).values())[0] for user in users]
    sorted_detailed_users = sorted(detailed_users, key=lambda u: u.message_count, reverse=True)
    best_friend = sorted_detailed_users[0]
    while True:
        if language == "English":
            choice = input("\nDo you want to know how many users you talked to in total? [Y/n] --> ")
        else:
            choice = input("\nVuoi sapere con quanti utenti hai parlato in totale? [Y/n] --> ")
        if choice.lower() == "y" or choice.lower() == "yes" or choice.lower() == "s" or choice.lower() == "si":
            all_users = client.fetchAllUsers()
            if language == "English":
                print(f"You talked with a total of {len(all_users)} users!")
            else:
                print(f"Hai parlato con un totale di {len(all_users)} utenti!")
            break
        elif choice.lower() == "n" or choice.lower() == "no":
            break
        else:
            if language == "English":
                print("You have not entered a valid choice!")
            else:
                print("Non hai inserito una scelta valida!")
    if language == "English":
        print(f"\nBest friend: {best_friend.name}, with a message count of {best_friend.message_count} messages!")
    else:
        print(f"\nMigliore amico: {best_friend.name}, con un conteggio messaggi di {best_friend.message_count} messaggi!")
    while True:
        if language == "English":
            choice = input("\nDo you want to send him a message? [Y/n] --> ")
        else:
            choice = input("\nVuoi inviargli un messaggio? [Y/n] --> ")
        if choice.lower() == "y" or choice.lower() == "yes" or choice.lower() == "s" or choice.lower() == "si":
            if language == "English":
                msg = input("Insert the message --> ")
            else:
                msg = input("Inserisci il messaggio --> ")
            client.send(Message(text=msg))
            break
        elif choice.lower() == "n" or choice.lower() == "no":
            break
        else:
            if language == "English":
                print("You have not entered a valid choice!")
            else:
                print("Non hai inserito una scelta valida!")
    if language == "English":
        print("Done!\n")
    else:
        print("Fatto!\n")
    client.logout()
Exemple #21
0
def send(message, fb):
    """
    Uses the facebook client to send a message to the group chat
    :param message: the message to send
    :param fb: the client used to send the msg
    """
    print("Sending:", message)
    fb.send(Message(text=message),
            thread_id=environ['THREAD_ID'],
            thread_type=ThreadType.GROUP)
Exemple #22
0
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)
Exemple #23
0
 def filter_add(message, user):
     print(user.name, message.text)
     if message.text == subscription_message:
         users.append(user)
         self.send(
             Message(text="{} est inscrit.".format(user.name)),
             thread_id=self.thread_id,
             thread_type=thread_type,
         )
     return False
Exemple #24
0
def fat(client, t_id, t_type):
    '''sends "mmmm" + fat wojak'''

    client.sendLocalImage(
        "photos/fat_wojak.png",
        Message(text="mmmmmmmmmmmmmmmm"),
        thread_id=t_id,
        thread_type=t_type,
    )

    return
Exemple #25
0
def lexus(client, t_id, t_type):
    '''sends "Guys who buy Lexus..." + stupid clapping wojak'''

    client.sendLocalImage(
        "photos/clapping_wojak.png",
        Message(text="Guys who buy Lexus cars in their 20's be like:"),
        thread_id=t_id,
        thread_type=t_type,
    )

    return
Exemple #26
0
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
Exemple #27
0
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
Exemple #28
0
def test_send_remote_files(client, catch_event, compare):
    files = ["image.png", "data.json"]
    text = "Files sent from remote"
    with catch_event("onMessage") as x:
        mid = client.sendRemoteFiles(
            ["https://github.com/carpedm20/fbchat/raw/master/tests/{}".format(f) for f in files],
            message=Message(text),
        )

    assert compare(x, mid=mid, message=text)
    assert subset(vars(x.res["message_object"]), uid=mid, author=client.uid, text=text)
    assert len(x.res["message_object"].attachments) == len(files)
Exemple #29
0
def test_send_local_files(client, catch_event, compare):
    files = ["image.png", "image.jpg", "image.gif", "file.json", "file.txt", "audio.mp3", "video.mp4"]
    text = "Files sent locally"
    with catch_event("onMessage") as x:
        mid = client.sendLocalFiles(
            [path.join(path.dirname(__file__), "resources", f) for f in files],
            message=Message(text),
        )

    assert compare(x, mid=mid, message=text)
    assert subset(vars(x.res["message_object"]), uid=mid, author=client.uid, text=text)
    assert len(x.res["message_object"].attachments) == len(files)
Exemple #30
0
def cron(group):
    if group in reminders:
        now = datetime.now()
        rl = reminders[group]
        to_del = []
        for i, r in rl.items():
            if r.date < now:
                group.send(Message(text=str(r)))
                to_del.append(i)
                group.delete(str(i))
        for i in to_del:
            del rl[i]