def plugin(srv, item): srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__, item.service, item.target) client = item.addrs[0] password = item.addrs[1] friend = item.addrs[2] fbclient = Client(client, password) friends = fbclient.searchForUsers(friend) ffriend = friends[0] srv.logging.debug("user %s" % (item.target)) text = item.message try: srv.logging.debug("Sending msg to %s..." % (item.target)) sent = fbclient.sendMessage(text, thread_id=ffriend.uid, thread_type=ThreadType.USER) srv.logging.debug("Successfully sent message") except Exception, e: srv.logging.error("Error sending fbchat to %s: %s" % (item.target, str(e))) return False
from fbchat import Client client = Client() async def main(): await client.start("<email>", "<password>") # Fetches a list of all users you're currently chatting with, as `User` objects users = await client.fetch_all_users() print(f"users' IDs: {[user.uid for user in users]}") print(f"users' names: {[user.name for user in users]}") # If we have a user id, we can use `fetch_user_info` to fetch a `User` object user = (await client.fetch_user_info("<user id>"))["<user id>"] # We can also query both mutiple users together, which returns list of `User` objects users = await client.fetch_user_info("<1st user id>", "<2nd user id>", "<3rd user id>") print(f"user's name: {user.name}") print(f"users' names: {[users[k].name for k in users]}") # `search_for_users` searches for the user and gives us a list of the results, # and then we just take the first one, aka. the most likely one: user = (await client.search_for_users("<name of user>"))[0] print(f"user ID: {user.uid}") print(f"user's name: {user.name}") print(f"user's photo: {user.photo}") print(f"Is user client's friend: {user.is_friend}")
from fbchat import Client from fbchat.models import * from getpass import getpass print(""" ---------------------------------------------- FBCID (Facebook Conversation Image Downloader) ---------------------------------------------- """) email = str(input('Enter email: ')) pswd = getpass('Enter password: '******'Logging in...') client = Client(email, pswd, logging_level=50) except FBchatUserError as e: print(e) sys.exit() thread_limit = 15 if client is not None and client.isLoggedIn(): print('Logged in as ' + email) threads = client.fetchThreadList(limit=thread_limit) for i in range(thread_limit): thread_info = client.fetchThreadInfo(threads[i].uid)[threads[i].uid] print('[{}] {}'.format(i, thread_info.name)) selected_thread = int(input('Select thread: '))
def fetchFBInformation(app, userid, fbemailid, fbpassword): #### # 0. Set base variables ############ messagefile_complete_name = "all_messages_" messagefile_complete_filetype = ".txt" ############ # 1. Login into the FB account ############################### try: # define a FB connector client = Client(fbemailid, fbpassword) # Update FBemailid for the <userid> updateFBEmailid(app, int(userid), fbemailid) # Update the process status to '2' for successful login updateProcessStatus(app, int(userid), '2') except Exception as wrongLoginCredentials: print("Wrong User name or password") return (-1) ######### # 2. Fetch chat-interlocutors of <userid> ############################################## interlocutors = client.fetchAllUsers() print("Number of Users: " + str(len(users))) # Update the process status to '3' for having fetched FB chat data updateProcessStatus(app, int(userid), '3') ######### # 3. Fetch chatHistories for all interlocutors of <userid> that happen after <maxTimeStamp>; if <maxTimeStamp> is "1" : fetch all ################################################################################################################################## # initialize a list for all conversation threads of <userid> conversations = [] # initialize a list of interlocutor uids with whom <userid> has more than 1 message exchanged interlocutor_uids = [] # fetch the timestamp when the last FB fetch happened and cast it to <int>-type maxTimestampDB = fetchTimestamp(app, int(userid)) maxTimestampDB = int(maxTimestampDB) # Fetch messages <userid> chats with and append it to <conversations> for interlocutor in interlocutors: try: # try to fetch the last 1000 messages from the conversation between <userid> and <interlocutor> threadMessages = client.fetchThreadMessages( thread_id=interlocutor.uid, limit=10000) messageCount = len(threadMessages) # if more than one message has been exchanged ... if (len(threadMessages) > 1): # remember thread messages in the <conversations>-list conversations.append( client.fetchThreadMessages(thread_id=interlocutor.uid)) # remember the interlocutor_uid interlocutor_uids.append(interlocutor.uid) except fetchFBchatException: #print("## Error ## ","UID: ",user.uid, " Name: ", user.first_name, " ", user.last_name, "# of msgs: ") pass # Error conversations that contain no messages (i.e. conversations started automatically by messenger after becoming friends on FB print("Fetched ", "conversations: " + str(len(conversations)), " userlist length: " + str(len(userlist))) ########## # 4. Extract all non-empty conversations which have not been fetched before ########################################################################## write_log("Threads Fetched. Start language classfication.") # set paths ## path that will contain all messages as a single file in JSON format #messagefolder_json = "./Messages_json/" # ## path that will contain all messages as a single file in plain text format #messagefolder_plain = "./Messages_plain/" # path that will contain all messages the user has ever sent in one single file per language used messagefolder_complete = "./ServerFeatures/Userdata/Messages_complete/" + str( userid) + "/" # file-name to store a message temporarily for language classification message_tempfile_path = "./ServerFeatures/Userdata/Messages_complete/" + str( uderid) + "/tempfile.txt" # initialize a list for the languages used in <userid>'s conversations languages = [] # initialize (WRITE WHAT) language_count = [] # initialize a counting variable for the considered conversations interlocutor_number = 0 # return value of the function (all English messages in one string) # VERIFY - probably the timestamps for the conversations max_message_timestamps = [] # create message folders if not existing yet #if not os.path.exists(messagefolder_json): # os.makedirs(messagefolder_json) #if not os.path.exists(messagefolder_plain): # os.makedirs(messagefolder_plain) if not os.path.exists(messagefolder_complete): os.makedirs(messagefolder_complete) # clear all message files if existent # TODO: this will have to be removed # otherwise, running the script multiple times will cause messages to appear multiple times in the files # TODO: change later for updating #for root, dirs, files in os.walk(messagefolder_json): # for file_ in files: # if file_.endswith(".txt"): # os.remove(os.path.join(root, file_)) #for root, dirs, files in os.walk(messagefolder_plain): # for file_ in files: # if file_.endswith(".txt"): # os.remove(os.path.join(root, file_)) # collect all *.txt files in <messagefolder_complete> # (only relevant if the user has stored FB messages in the past for root, dirs, files in os.walk(messagefolder_complete): for file_ in files: if file_.endswith(".txt"): os.remove(os.path.join(root, file_)) # for all conversations (with more than one message) for conversation in conversations: # set sub directory paths for each chat partner in the #userdir_json = messagefolder_json + "/" + str(userlist[user_number]) #userdir_plain = messagefolder_plain + "/" + str(userlist[user_number]) # ## make directories if not yet existent #if not os.path.exists(userdir_json): # os.makedirs(userdir_json) #if not os.path.exists(userdir_plain): # os.makedirs(userdir_plain)## # remember all thread messages, their predicted language, and the number of considered messages of the conversation conversation_messages = [] conversation_message_languages = [] conversation_message_counter = 0 text_returned_en = "" conversation_empty = True # for all messages in the conversation for message in conversation: # get message text, author, timestamp message_text = message.text message_author = message.author message_timestamp = message.timestamp # encode <message_text> to utf-8 if type(message_text) == 'unicode': message_text = message_text.encode('utf-8') elif type(message_text) == str: message_text.decode('utf-8').encode('utf-8') # remember the timestamp of the message max_message_timestamps.append(message_timestamp) # (e.g. exclude automatically generated call messages) # if <message_text> is not empty # AND # the message has not been fetched in the past (maxTimestampDB indicates the most recent point in time <userid> fetched FB messages # AND # if the message was sent by <userid> and not by <interlocutor> message_not_empty = (message_text != None) message_sent_by_userid = (message_author == client.uid) message_not_fetched_before = (int(message_timestamp) > int(maxTimestampDB)) if (message_not_empty & message_sent_by_userid & message_not_fetched_before): conversation_empty = False # set message file paths for the json and text message files #messagedir_plain = userdir_plain + "/" + message_timestamp + ".txt" #messagedir_json = userdir_json + "/" + message_timestamp + ".txt" # remove newlines (\n) and carriage returns (\r) (for language classification - otherwise this would produce multiple outputs) message_text = message_text.replace('\n', ' ').replace('\r', '') ## write message json file #message_dictionary = {'timestamp': message_timestamp, 'author_id': message_author, 'text': message_text} #with open(messagedir_json, "w") as outfile: # json.dump(message_dictionary, outfile) # outfile.close() # write message text file #with open(messagedir_plain, "w") as outfile: # outfile.write(message_text) # outfile.close() # put <message_text> into a temporary file for languge prediction with open(message_tempfile_path, "w") as tempfile: tempfile.write(message_text) # try to predict the message's language with the original fasttext algorithm try: message_language = check_output([ './ServerFeatures/Wordembedding/fastText-original/fasttext', 'predict', './ServerFeatures/Preprocessing/Languageprediction/pretrainedmodel.bin', message_tempfile_path ]) # remove newlines (\n) from <message_language> message_language = str(message_language).replace('\n', '') except CalledProcessError as e: raise RuntimeError( "command '{}' returned with error (code {}): {}". format(e.cmd, e.returncode, e.output)) # keep track of every language prediction for the conversation and count the messages in the conversation # e.g. # conversation_messages = [msg1, msg2, msg3] # conversation_message_languages = ['__label__en', '__label__de', '__label__en'] conversation_messages.append(message_text) conversation_message_languages.append(message_language) conversation_message_counter += 1 #### # 5. Filter out empty conversations ########################################3 if conversation_empty: continue # with the next iteration of the loop """ # this code only focuses on English conversations # extract the languages used in the conversation and their respective counts conversation_message_languages_and_count = [ ( conversation_messages_languages.count(language), language) for language in set(conversation_message_languages) ] # pick the majority language, max finds the maximum in the 0-th elements of the duples majority_language = max(conversation_message_languages_and_count)[1] """ #### # 6. Build separate chat histories for <userid> for each conversation language ############################################################################ conversation_languages = [] conversation_language_count = [] # for all recorded conversation languages for message_language in conversation_message_languages: message_language_known = False conversation_language_index = 0 # for for conversation_language in conversation_languages: if conversation_language == message_language: conversation_language_count[ conversation_language_index] = conversation_language_count[ conversation_language_index] + 1 message_language_known = True break conversation_language_index = conversation_language_index + 1 if (message_language_known == False): conversation_languages.append(message_language) conversation_language_count.append(1) # retrieve final conversation language for the whole conversation max_language_count = 0 conversation_language = '' conversation_language_index = 0 for x in conversation_languages: if (conversation_language_count[conversation_language_index] > max_language_count): max_language_count = conversation_language_count[ conversation_language_index] conversation_language = conversation_languages[ conversation_language_index] conversation_language_index = conversation_language_index + 1 #print("Final conversation language: ", conversation_language) # add conversation language use to the global language use of the user language_index = 0 language_known = False for language in languages: if language == conversation_language: language_count[language_index] = language_count[ language_index] + len(conversation_messages) language_known = True break if (language_known == False): languages.append(conversation_language) language_count.append(len(conversation_messages)) # append all conversation messages to the respective complete history with regard to the conversation language # format e.g.: "./ServerFeatures/Userdata/Messages_complete/testid/all_messages___label__en.txt" complete_history_path = messagefolder_complete + messagefile_complete_name + str( userid) + conversation_language + messagefile_complete_filetype # the conversation messages are encoded in 'utf-8', see above with open(complete_history_path, "a+") as complete_file: for conversation_message in conversation_messages: append_message = (conversation_message.decode('utf-8') + " ").encode('utf-8') complete_file.write(append_message) # append message to the return string if it is english // TODO: potentially change later if (conversation_language == '__label__en'): text_returned_en = text_returned_en + conversation_message + " " interlocutor_number += 1 # print("Conversation languages: ",conversation_languages) # print("Conversation language count: ",conversation_language_count) print("Overall languages used: ", languages) print("Overall languages used count:", language_count) # delete tempfile if (os.path.isfile(message_tempfile_path)): os.remove(message_tempfile_path) # Update the process status to '4' updateProcessStatus(app, int(userid), '4') ###### # 7. Extract language usage statistics of <userid> ################################## # for testing only # get language statistics msg_count_en = 0 msg_count_total = 0 index = 0 for language in languages: if (language == '__label__en'): msg_count_en = msg_count_en + language_count[index] msg_count_total = msg_count_total + language_count[index] index = index + 1 write_log("Finished language classification") ###### # 8. Update <maxTimeStamp> in the userinfo TABLE if necessary #################################################### complete_EN_history_path = messagefolder_complete + messagefile_complete_name + str( userid) + '__label__en' + messagefile_complete_filetype # if an English chat history path exists EN_chatHistory_exists = os.path.isfile(complete_EN_history_path) if EN_chatHistory_exists: new_non_empty_conversations_fetched = len(max_message_timestamps) > 0 if new_non_empty_conversations_fetched: print("Update maxTimeStamp in the userinfo TABLE") word_count_en = len(text_returned_en.split()) write_log( "Fetched {} Facebook messages. Number of english classified messages: {}. Number of english words: {}" .format(msg_count_total, msg_count_en, word_count_en)) # Update maxTimeStamp in the userinfo TABLE status = updateMessageTimestamp(app, int(userid), max(max_message_timestamps)) # return the chat history path for English conversations return complete_EN_history_path # return "-1" if no changes were made return "-1"
' :-)', ' Przyjacielu!', ' Kolego'] day_prefix = ['Dzień dobry ', 'Dobrego dnia ', 'Dobry dzień ', 'Miłego dnia ', 'Udanego dnia '] day_sufix = [' !', ' :)', ' <3', ' c;', ' ;>', ' Przyjacielu!', ' Kolego'] client=Client("YOUR_EMAIL ","YOUR_PASSWORD") client.send(Message('STARTED'), thread_id=client.uid, thread_type=ThreadType.USER) var = True while var == True: if(time.gmtime().tm_sec == 00 and time.gmtime().tm_min == 00 and time.gmtime().tm_hour == 22): for x in ids: user = client.fetchUserInfo(x)[x] interfix = user.first_name client.send(Message(text=night_prefix[random.randrange(len(night_prefix))]+interfix+night_sufix[random.randrange(len(night_sufix))]), thread_id=x, thread_type=ThreadType.USER) time.sleep(1) var = False var = True while var == True: if(time.gmtime().tm_sec == 00
from fbchat import Client from fbchat.models import * from fbchat import Message from fbchat import ThreadType client = Client('*****@*****.**','Spawndslyer13') if client.isLoggedIn(): print("Logins sucess") client.send(Message(text='Prueba'),thread_id="dlego.martinez",thread_type=ThreadType.USER) client.logout() else: print("Failed to log in")
print("Checking Operation System !") sleep(1) if "linux" not in linux : print("\n") slowprints1(colored("Linux is Required ","red")) slowprints1(colored("Microsoft Sucks =)","white")) print("\n") sys.exit(127) else : slowprints1(colored("[*] LINUX CONFIRMED ",'green')) sleep(1) os.system("clear && clear") _email = raw_input('\n USERNAME/EMAIL : ') _password = getpass.getpass(prompt='\n PASSWORD : '******'Click Enter to Continue ') def clear(): os.system('clear && clear') def main():
#export PATH=$PATH:/home/yaminul/Downloads/geckodriver-v0.26.0-linux64 (set geckodriver in my path) from fbchat import Client from fbchat.models import * import time import cleverbotfree.cbfree import sys cb = cleverbotfree.cbfree.Cleverbot() client=Client('your email id', 'password') client.isLoggedIn() print(format(client.uid)) user = client.searchForUsers(input("withwhom to chat:"))[0] print("user's name: {}".format(user.name)) #messages = client.fetchThreadMessages(thread_id= 'user.uid', limit=1) #for message in messages: temp = 'it' bot='it' try: cb.browser.get(cb.url) except: cb.browser.close() sys.exit() while True: cb.get_form() messages = client.fetchThreadMessages(thread_id= user.uid, limit=1) for message in messages: p=message.text if temp==p or bot==p: time.sleep(3) print("no reply") else: temp=message.text
from fbchat import Client from fbchat.models import * from datetime import datetime from threading import Timer from getpass import getpass from sys import argv p = "" try: p = argv[1] except: p = getpass() client = Client('*****@*****.**', p) group = client.fetchGroupInfo('2136630926368530') client.logout() user_ids = group['2136630926368530'].participants x = datetime.today() try: y = x.replace(day=x.day + 1, hour=0, minute=0, second=0, microsecond=0) except ValueError: y = x.replace(month=x.month + 1, day=1, hour=0, minute=0, second=0, microsecond=0) delta_t = y - x
#Made By George Browning using fbchat #github.com/MindTheGap1 from fbchat import Client from fbchat.models import * import time client = Client("email", "password") thread_id = 'groupid' thread_type = ThreadType.GROUP client.sendRemoteImage( 'https://media.giphy.com/media/l3q2zVr6cu95nF6O4/giphy.gif', message=Message(text="IT'S PARTY TIME!"), thread_id=thread_id, thread_type=thread_type) while True: client.changeThreadColor(ThreadColor.MESSENGER_BLUE, thread_id=thread_id) client.changeThreadEmoji('😡', thread_id=thread_id) time.sleep(0.1) client.changeThreadColor(ThreadColor.BILOBA_FLOWER, thread_id=thread_id) client.changeThreadEmoji('😈', thread_id=thread_id) time.sleep(0.1) client.changeThreadColor(ThreadColor.BRILLIANT_ROSE, thread_id=thread_id) client.changeThreadEmoji('😡', thread_id=thread_id) time.sleep(0.1) client.changeThreadColor(ThreadColor.CAMEO, thread_id=thread_id) client.changeThreadEmoji('😈', thread_id=thread_id) time.sleep(0.1) client.changeThreadColor(ThreadColor.DEEP_SKY_BLUE, thread_id=thread_id) client.changeThreadEmoji('😡', thread_id=thread_id) time.sleep(0.1)
def print_single_thread(client: Client, thread_id): messages = client.fetchThreadMessages(thread_id, limit=30) thread_info = client.fetchThreadInfo(thread_id) interlocutor = thread_info[thread_id] _print_thread_messages(client, messages, interlocutor)
from fbchat import Client from fbchat.models import * import pandas as pd import pygsheets import fb_link_settings as settings client = Client(settings.FACEBOOK_USERNAME, settings.FACEBOOK_PASSWORD) localpath = settings.LOCAL_PATH namedict={} names = settings.NAMES for name in names: namedict[client.searchForUsers(name)[0].uid] = name ## insert thread_id here. Fetches last 1000 messages — adjust as necessary messages=client.fetchThreadMessages(thread_id=settings.THREAD_ID,limit=1000) lines=[] cols=['Name','Title','Link','Source'] d=dict.fromkeys(cols) df1=pd.DataFrame(columns=cols) for message in messages: try: m=message.attachments[0] info=[namedict[message.author],m.title,m.original_url,m.source]
from fbchat import Client from fbchat.models import * import datetime import time import random from twilio.rest import Client as MyTwilioClient # FaceBook Chat info fb_client = Client('use your facebook email address', 'facebook password') thread_id = 'id for thread. open chat in facebook and look for /t/<chat id>' thread_type = ThreadType.USER # can use ThreadType.GROUP for a group chat # Twilio account info account_sid = 'twilio account SID' auth_token = 'twilio authentication token' twilio_client = MyTwilioClient(account_sid, auth_token) my_twilio_number = 'your twilio phone number' my_cell_number = 'your cell phone number' def day_and_time(): today_var = datetime.datetime.now().strftime('%A') if today_var == 'Monday' or 'Tuesday' or 'Thursday' or 'Friday': right_now_time = datetime.datetime.now().strftime('%H:%M') if right_now_time == '07:15': daily_message() else: time.sleep(60) day_and_time()
# -*- coding: UTF-8 -*- from fbchat import Client from fbchat.models import * client = Client("<email>", "<password>") thread_id = '1234567890' thread_type = ThreadType.GROUP # Will send a message to the thread client.send(Message(text='<message>'), thread_id=thread_id, thread_type=thread_type) # Will send the default `like` emoji client.send(Message(emoji_size=EmojiSize.LARGE), thread_id=thread_id, thread_type=thread_type) # Will send the emoji `👍` client.send(Message(text='👍', emoji_size=EmojiSize.LARGE), thread_id=thread_id, thread_type=thread_type) # Will send the sticker with ID `767334476626295` client.send(Message(sticker=Sticker('767334476626295')), thread_id=thread_id, thread_type=thread_type) # Will send a message with a mention
from fbchat import Client from fbchat.models import * username = "******" password = "******" def msg_fn(): msg = "What's up ningen!" for i in range(1000): msg += "What's up ningen!" return msg my_msg = msg_fn() client = Client(username, password) client.send(Message(text=my_msg), thread_id='2651262271654809', thread_type=ThreadType.GROUP)
from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.options import Options import time from fbchat import Client, log from fbchat.models import * options = webdriver.ChromeOptions() #options.add_argument('headless') driver = webdriver.Chrome(ChromeDriverManager().install()) #driver = webdriver.Chrome(options=options) client = Client("username", "password") users = client.fetchAllUsers() threads = client.fetchThreadList() driver.get( "https://www.kv.ee/?act=search.simple&last_deal_type=1&orderby=cdwl&deal_type=1&search_type=old" ) kirjeldus = "" i = 0 while (i != 30): print(i) i += 1 time.sleep(1) if (i == 29): driver.refresh() refreshedKirjeldus = driver.find_element_by_xpath( "/html/body/div[2]/div/div[2]/div[2]/table/tbody/tr[1]/td[2]/h2/a" ).text if (kirjeldus != refreshedKirjeldus):
def login(self): with open('facebookbot_account') as f: self.facebook_account = json.loads(f.read()) self.facebook_client = Client(self.facebook_account['id'], self.facebook_account['password'])
if (is_valid_note(social_media_dict, voice_note)): key = voice_note.split(' ')[1] webbrowser.open(social_media_dict.get(key)) else: os.system('explorer C:\\"{}"'.format( voice_note.replace('open ', '').replace('launch', ''))) continue elif is_valid_google_search(voice_note): print('i google search....') playsound('mp3/vox/search_1.mp3') google_search_result(voice_note) continue elif 'send message on facebook' in voice_note: client = Client('9355242300', 'enter facebook password here') no_of_friends = 1 for i in xrange(no_of_friends): name = str(raw_input("Name: ")) friends = client.searchForUsers(name, 5) # return a list of names friend = friends[0] print(friend.uid) msg = str(raw_input("Message: ")) sent = client.send(Message(text=msg), thread_id=friend.uid, thread_type=ThreadType.USER) if sent: print("Message sent successfully!") client.logout()
from fbchat import Client from fbchat.models import * # get credentials with open("credentials.txt", "r") as f: lines = f.readlines() username = lines[0].rstrip() password = lines[1].rstrip() my_uid = lines[2].rstrip() f.close() # open client client = Client(username, password) # send message client.send(Message(text='Time to drink water!'), thread_id=my_uid, thread_type=ThreadType.USER) client.logout() # use these lines if you need to find a friend's ID (put friend's name as argument) # user = client.searchForUsers('')[0] # print('user ID: {}'.format(user.uid)) # print(user)
# -*- coding: UTF-8 -*- from fbchat import Client from fbchat.models import * client = Client("<email>", "<password>") # Fetches a list of all users you're currently chatting with, as `User` objects users = client.fetchAllUsers() print("users' IDs: {}".format([user.uid for user in users])) print("users' names: {}".format([user.name for user in users])) # If we have a user id, we can use `fetchUserInfo` to fetch a `User` object user = client.fetchUserInfo("<user id>")["<user id>"] # We can also query both mutiple users together, which returns list of `User` objects users = client.fetchUserInfo("<1st user id>", "<2nd user id>", "<3rd user id>") print("user's name: {}".format(user.name)) print("users' names: {}".format([users[k].name for k in users])) # `searchForUsers` searches for the user and gives us a list of the results, # and then we just take the first one, aka. the most likely one: user = client.searchForUsers("<name of user>")[0] print("user ID: {}".format(user.uid)) print("user's name: {}".format(user.name)) print("user's photo: {}".format(user.photo)) print("Is user client's friend: {}".format(user.is_friend)) # Fetches a list of the 20 top threads you're currently chatting with
# If there is no user id -> exit if not '-i' in myargs: print("No User Id") sys.exit(0) # If there is no user name -> exit if not '-u' in myargs: print("No User Name") sys.exit(0) # If there is no password -> exit if not '-p' in myargs: print("No User Password") sys.exit(0) # Transfer the values user_id = myargs['-i'] username = myargs['-u'] password = myargs['-p'] # Load previous cookies session_cookies = json.load(open("session.json")) # Open the Client Object client = Client(username, password,session_cookies=session_cookies) try: specific_user_loop(user_id) except KeyboardInterrupt: print >> sys.stderr, "\nExiting by User Request.\n" sys.exit(0)
import time import requests from fbchat import Client from getpass import getpass from fbchat.models import * import keyboard #log into messenger username = str(input("Username: "******"pass: "******"r") for word in txt: #formulate message msg = word print(msg) if (msg == ""): continue if keyboard.is_pressed("esc"): break #messenger api ctrls client.send(Message(text=msg), thread_id=1000831126693209, thread_type=ThreadType.GROUP)
def addingLoop(self): while(self.addQueue.__len__() != 0): Client.addUsersToGroup(self, self.addQueue.pop(), self.CONF_ID) self.addFlag = False
def __init__(self, thread, login, password): self.client = Client(login, password) self.thread = thread
try: data = check(msg, thread=thread_id, ttype=thread_type, name=name, author=author_id, nickname=nickname) if data: if '#' in thread_name: logging.info('Replied in group: {}'.format(thread_name)) else: logging.info('Replied privately to {}'.format(thread_name)) await self.send(Message(text=data), thread_id=thread_id, thread_type=thread_type) except Exception as e: await self.send(Message(text=e), thread_id=thread_id, thread_type=thread_type) traceback.print_exc() await self.react_to_message(message_id, MessageReaction.SAD) pass send = Client() def say(data): logging.info('Saying {}'.format(data)) client.start(conf.bot_user, conf.bot_password) client.send(Message(text=data), thread_id=100039637672981, thread_type=ThreadType.USER) client.logout() loop = asyncio.get_event_loop() client = PlexBot(loop=loop) async def main(): await client.start(conf.bot_user, conf.bot_password) client.listen() # we need to update the session cookie for say.py cookie = client.get_session() with open('.cookie', 'w') as kapsel: kapsel.write(str(cookie))
print('trade_amount = ' + str(trade_amount)) trade_string = re.sub('[^-.@$%_a-zA-Z0-9]', " ", trade_string) print(trade_string) if (trade_amount >= float(config['cardsphere']['package_value'])): alert_user = True packageBody = x.find_element_by_class_name('package-body') cards = packageBody.find_elements_by_class_name('cardpeek') for y in cards: firstCard = y.text print(firstCard) trade_string += firstCard + " " print(trade_string) break #send facebook message if (alert_user == True): fuser = config['facebook']['username'] fpass = config['facebook']['password'] client = Client( fuser, fpass, user_agent= "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko" ) client.send(Message(text=trade_string), thread_id=config['facebook']['message_id'], thread_type=ThreadType.USER) client.logout() browser.quit()
import secrets, time, Clients, os from fbchat import Client from fbchat.models import * from getpass import getpass START_MESSAGE = "start" STOP_MESSAGE = "stop" WELCOME_MESSAGE = "Welcome! This is an automated message to start off this grocery ordering notification system\nSend me 'start' to begin receiving notifications" NOTIFY_MESSAGE = "Delivery Time Slot Available! https://delivery.realcanadiansuperstore.ca/ \n\n Notifications have automatically been turned OFF. To receive notifications again, please send me 'start'" UNRECOGNIZED_INPUT_MESSAGE = "I'm sorry I don't recognize what you typed.\nSend me 'start' to recieve delivery time notifications." CHANGED_TO_ACTIVE_MESSAGE = "Ok! You'll receive notifications about open delivery times.\nSend me 'stop' to NOT receive notifications anymore." CHANGED_TO_INACTIVE_MESSAGE = "Ok! You won't receive any notifications about open delivery times anymore.\nSend me 'start' to receive notifications again." fbClient = Client(secrets.FB_EMAIL, getpass()) def initAllClients(): clientList = Clients.getClientList() for i in clientList: if(Clients.getInitilized(i) == 0): name = fbClient.searchForUsers(i['name'])[0] sendMessengerMessage(WELCOME_MESSAGE, name) i['initilized'] = 1 def sendFBNotifications(activatedPostalCode): t = time.localtime() currentTime = time.strftime("%H:%M:%S", t) clientList = Clients.getClientList() for user in clientList: #Only send to client if active if(Clients.getPostalCode(user) == activatedPostalCode and Clients.getStatus(user)):
import requests from bs4 import BeautifulSoup from fbchat import Client from fbchat.models import * import time client = Client('*****@*****.**', 'Pythonisbest') def get_count(): url = 'https://onemocneni-aktualne.mzcr.cz/covid-19' con = requests.get(url).text soup = BeautifulSoup(con) count = [article.text for article in soup.find_all('p')] return [count[7], count[9], count[11]] while True: if time.localtime().tm_hour == 13 and time.localtime( ).tm_min == 4 and time.localtime().tm_sec == 0: client.send(Message( text= f'celkem nakazenych - {get_count()[0]}\nCelkovy pocet vylecenych - {get_count()[1]}\nCelkovy pocet umrti - {get_count()[2]}' ), thread_id='2674445732584644', thread_type=ThreadType.GROUP)
# -*- coding: UTF-8 -*- from fbchat import Client from fbchat.models import * sender_email = '...' sender_password = '******' client = Client(sender_email, sender_password) print('Own id: {}'.format(client.uid)) client.sendMessage('Hi me! from Python Chat Bot', thread_id=client.uid, thread_type=ThreadType.USER) client.logout()
def __init__(self, **kwargs): self.email = kwargs['email'] self.password = kwargs['password'] self.client = Client(self.email, self.password)
def mesend(s): client = Client('*****@*****.**', 'shivam1998@@') client.send(Message(text=str(s)), thread_id=client.uid, thread_type=ThreadType.USER) client.logout()
message_object=None, thread_id=None, thread_type=ThreadType.USER, **kwargs): self.markAsRead(author_id) log.info("Message {} from{} in {}".format(message_object, thread_id, thread_type)) #Establish connection self.apiaiCon() mesText = message_object.text self.request.query = mesText response = self.request.getresponse() obj = json.load(response) reply = obj['result']['fulfillment']['speech'] if author_id != self.uid: self.send(Message(text=reply), thread_id=thread_id, thread_type=thread_type) self.markAsDelivered(author_id, thread_id) Client = Jarvis('*****@*****.**', 'soccerdude1') Client.listen()