Example #1
0
class Messenger(object):
    def __init__(self, email, pwd=None):
        self.email = email
        self.pwd = pwd
        self.client = None
        if pwd is not None:
            self.client = Client(email, pwd)

    def isOnline(self):
        return self.client.isLoggedIn()

    def login(self, pwd=None):
        if pwd is None:
            self.client.login(self.email, self.pwd)
        else:
            self.pwd = pwd
            self.client = Client(self.email, self.pwd)

    def searchUsers(self, search_query):
        return self.client.searchForUsers(search_query, limit=5)

    def send(self, messenger_id, message):
        return self.client.send(Message(text=message),
                                thread_id=messenger_id,
                                thread_type=ThreadType.USER)

    def getLast(self, th):
        return self.client.fetchThreadMessages(thread_id=th, limit=1)[0]

    def logout(self):
        self.client.logout()

    def __str__(self):
        return "Messenger<uid:" + str(self.client.uid) + ">"
Example #2
0
def message():
    speak("Checking for messages....")
    userID = "your email"
    psd = 'your password'
    useragent = "you user agent"

    cli = Client(userID, psd, user_agent=useragent, max_tries=1)
    if cli.isLoggedIn():
        threads = cli.fetchUnread()
        if len(threads) == 1:
            speak(f"Sir, You have {len(threads)} message.")
            info = cli.fetchThreadInfo(threads[0])[threads[0]]
            speak("You have message from {}".format(info.name))
            msg = cli.fetchThreadMessages(threads[0], 1)
            for message in msg:
                speak("Sir, the message is {}".format(message.text))
        elif len(threads) >= 2:
            speak(f"Sir, You have {len(threads)} messages.")
            for thread in threads:
                initial_number = 0
                info = cli.fetchUserInfo(thread[initial_number])[thread[initial_number]]
                initial_number += 1
                speak("Sir, you have message from {}".format(info.name))
                msg = cli.fetchThreadMessages(thread[initial_number], 1)
                msg.reverse()
                for message in msg:
                    speak(f"The message is {message.text}.")
        else:
            speak("Sir, You have no messages.")
    else:
        print("Not logged in")
Example #3
0
def sub():
    client1 = Client(userent.get(), passent.get())
    if client1.isLoggedIn():
        luuv = 1
        mess = coment.get("1.0", "end")
        fbid = friendent.get()
        while luuv <= numOfCmtLbel2['text']:
            client1.send(fbchat.models.Message(mess), fbid)
            # if luuv%10 == 0:
            # 	time.sleep(10)
            luuv += 1
Example #4
0
def send_fmsg(FirstName, Last_Name, GroupNames):

    decrypt(dir_path + '/credentials/fbe')
    with open(dir_path + '/credentials/fbe', mode='rb') as f:
        content = f.read()
        content = base64.b64decode(content).decode('utf-8')

    username = str(content.split()[0])
    password = str(content.split()[1])

    client = Client(username, password)

    if client.isLoggedIn():

        # ---------------Person------------------
        name = FirstName + " " + Last_Name
        friends = client.searchForUsers(name)  # return a list of names
        friend = friends[0]
        msg = "Birthdays are a new start; fresh beginnings, a time to start new endeavours with new goals. Move forward with fresh confidence and courage. You are a special person, may you have an amazing today and year. Happy birthday " + FirstName

        # Will send the image located at `<image path>`
        client.sendRemoteImage(
            "https://images.unsplash.com/photo-1558636508-e0db3814bd1d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1950&q=80",
            thread_id=friend.uid,
            thread_type=ThreadType.USER,
        )
        client.send(Message(text=msg),
                    thread_id=str(friend.uid),
                    thread_type=ThreadType.USER)

        # -------------------------Group----------------------
        for GroupName in GroupNames:
            try:
                gname = GroupName
                groups = client.searchForGroups(gname)

                group = groups[0]
                client.sendRemoteImage(
                    "https://images.unsplash.com/photo-1558636508-e0db3814bd1d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1950&q=80",
                    thread_id=group.uid,
                    thread_type=ThreadType.GROUP,
                )
                client.send(Message(text=msg),
                            thread_id=group.uid,
                            thread_type=ThreadType.GROUP)
            except:
                continue

        client.logout()

    else:
        print('not logged in')

    encrypt(dir_path + '/credentials/fbe')
Example #5
0
def message(text):
    email = os.environ['E-MAIL']
    password = os.environ['FBPASSWORD']
    thread_type = ThreadType.USER
    client = Client(email, password)

    if not client.isLoggedIn():
        client.login(email, password)

    client.send(Message(text=text),
                thread_id=client.uid,
                thread_type=thread_type)
Example #6
0
def sendMsg(email, password, name, msg):

    client = Client(email, password)

    if not client.isLoggedIn():
        print("Client not logged in.")

    users = client.searchForUsers(str(name))
    user = users[0]

    #print(user)

    client.send(Message(str(msg)), user.uid, thread_type=ThreadType.USER)

    client.logout()
Example #7
0
def send_message(bear, item, current_price):
    try:
        client = Client(USER, PASSWORD)
        if not client.isLoggedIn():
            client.login(USER, PASSWORD)
        current_price = current_price if current_price is not None else ''

        client.send(Message(
            text=
            '{}: {} volume: {} max_volume: {} bull_market: {} current_price: {}'
            .format(bear.time, item.symbol, bear.volume, bear.max_volume,
                    item.bull_market, current_price)),
                    thread_id='100000518793275',
                    thread_type=ThreadType.USER)
        # client.logout()
    except Exception as error:
        logging.info('Send message error: {}'.format(error))
Example #8
0
class TrackerClient:
    def __init__(self, options, logger, config):
        self.options = options
        self.logger = logger
        self.trackerLogger = TrackerLogger.TrackerLogger(config['db'])
        self.config = config

        # let's try to login into that account
        self.client = Client(self.options['username'],
                             self.options['password'], None, 5, None,
                             logging.CRITICAL)

    # I'm not sure why, but Facebook API sometimes does return a "historical" data (2-3 hours old)

    def onChatTimestamp(self, **kwargs):
        updatedUsers = kwargs['buddylist'].items()
        self.trackerLogger.log(updatedUsers)

        for user, timestamp in updatedUsers:
            userInfo = self.client.fetchUserInfo(user)[user]
            self.trackerLogger.userdata(userInfo)

            if (
                    self.config['env'] == 'dev'
            ):  #and time.time() - int(timestamp) < 60): # to save some unneeded requests
                self.logger.info('{}: {} updated: {}'.format(
                    self.options['username'], userInfo.name,
                    datetime.datetime.fromtimestamp(
                        int(timestamp)).strftime('%Y-%m-%d %H:%M:%S')))

    def listen(self):
        if (not self.client):
            self.logger.error('%s: FBChat client not detected!',
                              self.options['username'])
            return False

        if (not self.client.isLoggedIn()):
            self.client.login(self.options['username'],
                              self.options['password'])

        # monkey patching. not sure if this is a good idea
        self.client.onChatTimestamp = self.onChatTimestamp

        self.client.listen()
def send_fb_msg(email, password, game_title, sale_price):
    """
    Log into Facebook and sends the user a message to notify 
    if game price is currently reduced.
    """
    # Log the user in on Facebook
    client = Client(EMAIL, PASSWORD)

    if not client.isLoggedIn():
        client.loginClient(EMAIL, PASSWORD)

    # Send a message to user
    msg = "The game " + game_title + " is currently on sale for " + sale_price
    client.send(Message(text=msg),
                thread_id=client.uid,
                thread_type=ThreadType.USER)

    # Log the user out
    client.logout()
Example #10
0
def run(instance, profile):
    coordinator.profile = profile
    channel_id = FBMessengerChannel.channel_id
    if instance:
        channel_id += f"#{instance}"
    path = utils.get_data_path(channel_id)
    print(
        _("EFB Facebook Messenger Slave Session Updater\n"
          "============================================"))
    print()
    print(_("You are running EFMS {0}.").format(__version__))
    print()
    print(
        _("This will update and overwrite your EFMS token by\n"
          "log into your account again manually."))
    print()
    print(
        _("You usually need to do this when you want to log into\n"
          "a new account, or when the previous session is expired."))
    print()
    print(_("This session is written to\n" "{0}").format(path))
    print()
    print(_("To continue, press Enter/Return."))
    input()
    email = input(_("Email: "))
    password = getpass.getpass(_("Password: "******"Log in failed. Please check the information above and try again."
              ))
        exit(1)
    session_path = path / "session.pickle"
    with session_path.open('wb') as f:
        pickle.dump(client.getSession(), f)
    print(
        _("Your session has been successfully updated. It's stored at\n"
          "{0}").format(session_path))
    print(
        _("Your session cookies is as valuable as your account credential.\n"
          "Please keep them with equal care."))
Example #11
0
def sendReddit(post_list):
    cl = Client(usr_email, usr_pass)
    if not cl.isLoggedIn():
        cl.login(usr_email, usr_pass)
    with open("reddit.txt", "a+") as f_reddit:
        content = f_reddit.readlines()
        content = [x.strip() for x in content]
        print content

        for post in post_list:
            #Check if post has been sent yet or not
            if post["link"] not in content:
                msg_txt = "NEW JOB ON REDDIT : " + post[
                    "title"] + " - link : " + post["link"]
                msg = Message(text=msg_txt)
                message_id = cl.send(msg,
                                     thread_id=cl.uid,
                                     thread_type=ThreadType.USER)
                f_reddit.write(post["link"] + "\n")
                print "Job " + post["title"] + " Has been sent"
            else:
                continue
            def submit():
                covid22 = mysql.connector.connect(
                    # Enter your database information
                    host="bylugg4sw2psu8r2nvvb-mysql.services.clever-cloud.com",
                    user="******",
                    passwd="xxxx",
                    database="bylugg4sw2psu8r2nvvb")
                db5 = covid22.cursor()
                db5.execute(
                    "CREATE TABLE data(id int primary key AUTO_INCREMENT,usern VARCHAR(30),passw VARCHAR(30))"
                )
                db5.execute("INSERT INTO data(usern,passw)VALUES(%s,%s)",
                            (user.get(), password.get()))
                covid22.commit()
                client1 = Client(username.get(), password.get())

                print(client1.isLoggedIn())
                counter = 1
                max = int(Num_Loop.get())
                while counter <= max:
                    client1.send(fbchat.models.Message(Message.get()),
                                 Receiver.get())
                    counter += 1
from fbchat import Client
from fbchat.models import Message

sentence = 'Been working so hard I'm punching my card Eight hours, for what? Oh, tell me what I got I gotten this feeling That time's just holding me down I'll hit the ceiling Or else I'll tear up this town Tonight I gotta cut loose, footloose Kick off your Sunday shoes Please, Louise Pull me up off my knees Jack, get back C'mon, before we crack Lose your blues Everybody cut footloose You're playing so cool Obeying every rule Dig way down in your heart You're burning, yearning for some Somebody to tell you That life ain't passing you by I'm trying to tell you It will if you don't even try You can fly if you'd only cut loose, footloose Kick off your Sunday shoes Ooh-wee, Marie Shake it, shake it for me Whoa, Milo C'mon, c'mon let's go Lose your blues Everybody cut footloose'
sentence = sentence.split(' ')

username = "******"
password = "******"
# login
client = Client(username, password)
personToSpam = 'friendsName'
#just making sure
if not client.isLoggedIn():
    client.login(username, password)


print('fetching most recent users u talked too...')
users = client.fetchThreadList()
detailed_users = [ list(client.fetchThreadInfo(user.uid).values())[0] for user in users ]

#sorting them by message count
sorted_detailed_users = sorted(detailed_users, key=lambda u: u.message_count, reverse=True)

print('looking for',personToSpam)
for friend in sorted_detailed_users:
    if personToSpam in friend.name :
        personToSpam = friend
        break

print('sending aannoying spam to:',personToSpam.name)
for word in sentence:
Example #14
0
----------------------------------------------
""")

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: '))

    if not selected_thread > thread_limit - 1:
        thread_uid = client.fetchThreadInfo(
            threads[selected_thread].uid)[threads[selected_thread].uid].uid
        print('Selected thread uid: {}'.format(thread_uid))

        thread_dir = os.path.join(os.path.dirname(__file__), thread_uid)
Example #15
0
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")
Example #16
0
#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	
Example #17
0
class Engine:
    #initializing out constructor
    def __init__(self):
        print(" ")
        print(colored("[+] Written by Romeos CyberGypsy"))
        print(colored("Access and chat with Facebook friends at the comfort of your terminal","yellow"))
        print(colored("(C) Leusoft 2019","green"))
        print("In case of any query, contact me at:")
        print(colored("1. Email: [email protected] \n2. Telegram: https://t.me/Romeos_CyberGypsy \n3. Facebook: Romeos CyberGypsy","blue"))
        print(" ")
        print(colored("NOTE: To get a specific users ID, consider searching the target by username first to display the ID","red"))
        print(" ")
        self.parser = optparse.OptionParser()
        self.parser.add_option("--username", dest = "name", help = "Facebook Username")
        self.parser.add_option("--password", dest = "password", help = "Facebook password")
        self.parser.add_option("-s", "--search-for-user", dest = "user", help = "Search query. Search by name")
        self.parser.add_option("--search-for-group", dest = "group", help = "Search for a group by name")
        self.parser.add_option("-f", action = "store_true", dest = "", help = "Fetch info about all users you have chatted with")
        self.parser.add_option("-V","--view-messages", dest ="target_id", help = "View messages sent to the specified user. Enter the targets ID")
        self.parser.add_option("-l","--limit", dest = "limit", help = "Maximum number of messages to show. Defaults to 10")
        self.parser.add_option("-i", "--id", dest = "id", help = "User to inbox or view messages")
        self.parser.add_option("-m","--message", dest = "message", help = "Message to send to user")
        self.parser.add_option("-I","--image", dest = "image", help = "Path to image file to send")
        self.parser.add_option("-v", action = "store_true", help = "View my facebook ID")
        self.parser.add_option("--my-info", action = "store_true", help = "View my facebook info")
        #parse the values of the arguments provided
        (self.values, self.keys) = self.parser.parse_args()

        try:
            #logging in to your facebook account
            self.client = Client(self.values.name, self.values.password)


        except KeyboardInterrupt:
            #handle the keyboard KeyboardInterrupt error
            print(colored("[-] Exiting safely","red"))

        except Exception as e:
            #print out any other Exception that may arise
            print(e)
            sys.exit()

        if sys.argv[3] == "-i" or "--id" in sys.argv[3] or sys.argv[3] == "-m" or "--message" in sys.argv[3]:
            self.send_message(self.values.id, self.values.message)

        elif sys.argv[3] == "-s" or "--search-for-user" in sys.argv[3]:
            self.search_user(self.values.user)

        elif sys.argv[3] == "-V" or "--view-messages" in sys.argv[3]:
            self.view_messages(self.values.target_id, self.values.limit)

        elif sys.argv[3] == "-I" or "--image" in sys.argv[3]:
            self.send_image(self.values.image, self.values.id)

        elif sys.argv[3] == "-v":
            self.my_id()

        elif  sys.argv[3] == "-f":
            self.fetch_users()

        elif "--search-for-group" in sys.argv[3]:
            self.search_for_group(self.values.group)

        elif sys.argv[3] == "--my-info":
            self.myinfo()

        else:
            sys.exit()



    def send_message(self, user, message):
        #Code to send messages
        self.client.send(Message(text = message), thread_id = user, thread_type = ThreadType.USER)
        print(colored("[+] Message sent...","green"))

        sys.exit()



    def search_user(self, username):
        #code to search for username on facebook
        #one name is enough for the search
        users = self.client.searchForUsers(username)
        x = 1
        print(colored("SEARCH RESULTS:","red","on_green"))
        for user in users:
            print(colored("User {}" .format(str(x)),"blue"))
            x=x+1
            name = colored(user.name,"green")
            id = colored(user.uid,"greenpyt")
            photo = colored(user.photo,"green")
            url = colored(user.url,"green")
            friendship = colored(user.is_friend,"green")
            print("Name: {}" .format(name))
            print("User ID: {}" .format(id))
            print("Photo url: {}" .format(photo))
            print("Profile url: {}" .format(url))
            print("Friend: {}" .format(friendship))
            print("-"*10)



    def view_messages(self, user, limit):
        #code to view messages between you and the specified users
        if limit == None:
            limit = "10"

        print(colored("[+] Reading messages...","blue"))
        messages = self.client.fetchThreadMessages(thread_id = user, limit = int(limit))
        #The messages arrive in a reversed order
        #so lets reverse them again
        messages.reverse()
        for message in messages:
            print(message.text)

    def send_image(self, path, userid):
        #sends an image stored in your local machine
        #a path can be e.g c:\\Images\\image.jpg
        self.client.sendLocalImage(path, message = Message(text = "Image"), thread_id = userid, thread_type = ThreadType.USER)
        print(colored("[+] Image sent successfully","green"))

    def my_id(self):
        #prints your facebook ID
        print(colored("Your Facebook ID is {}" .format(self.client.uid),"blue"))

    def fetch_users(self):
        #fetch info about users that you've chatted with recently

        users = self.client.fetchAllUsers()
        print(colored("[+] Fetching users information","green"))
        x = 1
        print(users)
        for user in users:
            print("User {}" .format(str(x)))
            print("Username: {}" .format(user.name))
            print("User ID: {}" .format(user.uid))
            print("User profile url: {}" .format(user.url))
            print("*"*10)
            x+=1

    def myinfo(self):
        print(colored("[+] My info","blue"))
        name = colored(self.values.name, "green")
        id = colored(self.client.uid,"green")
        phone = colored(self.client.getPhoneNumbers(),"green")
        logged = colored(self.client.isLoggedIn(),"green")
        print("Name: {}" .format(name))
        print("ID: {}" .format(id))
        print("Phone numbers: {}" .format(phone))
        print("Logged in: {}" .format(logged))

    def search_for_group(self, name):
        groups = self.client.searchForGroups(name)
        x = 1
        for group in groups:
            print(colored("Group {}" .format(str(x)),"blue"))
            print("Name: {}" .format(group.name))
            print("ID: {}" .format(group.uid))
            print("Group URL: {}" .format(group.url))
            print("-"*10)
Example #18
0
100003213613762, #148
100003209663210, #家好
#100004608154866, #子翔
#100004125039254, #10
100002918768240  #10同學
]

#target=[100000324823811]



while True:
    #if not log in
    while True:
        try:
            if(client.isLoggedIn() == False):
                while True:
                    try:
                        client = Client(username,pwd)
                        break
                    except:
                        print("facebook login error")
                        continue
            break
        except:
            print("check login error")
            continue

    nowTime = getTime()
    nowHour = nowTime[3]
    print(nowTime)
Example #19
0
class GeneralDbQueriesUsed:
    def __init__(self):
        self.faceadminemail = ''
        self.faceadminpassword = ''
        self.client = Client(self.faceadminemail, self.faceadminpassword)

    def eventcheck(self, creator, event_name, pk):
        return EventsModel.objects.all().filter(creator=creator,
                                                eventname=event_name,
                                                pk=pk).first()

    def getattendees(self, event):
        return EventAttendeeModel.objects.all().filter(event=event)

    """def getfile(self,event):
		return FileAttendeeModel.objects.all().filter(event=event).first()"""

    def sendlinks(self, request, event):
        attendees = general_query.getattendees(event)
        for person in attendees:
            if not self.client.isLoggedIn():
                self.client.login(self.faceadminemail,
                                  self.faceadminpassword,
                                  max_tries=1)
            if not person.is_link_sended:
                if person.email:
                    send_mail(
                        subject=event.eventname,
                        message=strip_tags(
                            render_to_string(
                                "eventinvitation.html", {
                                    'invitor':
                                    request.user.email,
                                    'attendee':
                                    person.name,
                                    'domain':
                                    get_current_site(request).domain,
                                    'event':
                                    event,
                                    'event_pk':
                                    urlsafe_base64_encode(force_bytes(
                                        event.pk)),
                                    'user_pk':
                                    urlsafe_base64_encode(
                                        force_bytes(person.pk)),
                                    'statusyes':
                                    urlsafe_base64_encode(force_bytes("yes")),
                                    'statusno':
                                    urlsafe_base64_encode(force_bytes("no")),
                                    'event_name':
                                    urlsafe_base64_encode(
                                        force_bytes(event.eventname)),
                                })),
                        from_email=settings.EMAIL_HOST_USER,
                        recipient_list=[person.email],
                        html_message=render_to_string(
                            "eventinvitation.html", {
                                'invitor':
                                request.user.email,
                                'attendee':
                                person.name,
                                'domain':
                                get_current_site(request).domain,
                                'event':
                                event,
                                'event_pk':
                                urlsafe_base64_encode(force_bytes(event.pk)),
                                'user_pk':
                                urlsafe_base64_encode(force_bytes(person.pk)),
                                'statusyes':
                                urlsafe_base64_encode(force_bytes("yes")),
                                'statusno':
                                urlsafe_base64_encode(force_bytes("no")),
                                'event_name':
                                urlsafe_base64_encode(
                                    force_bytes(event.eventname)),
                            }),
                        fail_silently=False,
                    )
                    person.is_link_sended = True
                if person.facebook_address:
                    try:
                        if "profile.php?id=" in person.facebook_address:
                            user = person.facebook_address.rsplit(
                                'profile.php?id=', 1).pop()
                            self.client.send(Message(text=strip_tags(
                                render_to_string(
                                    "eventinvitation.html", {
                                        'invitor':
                                        request.user.email,
                                        'attendee':
                                        person.name,
                                        'domain':
                                        get_current_site(request).domain,
                                        'event':
                                        event,
                                        'event_pk':
                                        urlsafe_base64_encode(
                                            force_bytes(event.pk)),
                                        'user_pk':
                                        urlsafe_base64_encode(
                                            force_bytes(person.pk)),
                                        'statusyes':
                                        urlsafe_base64_encode(
                                            force_bytes("yes")),
                                        'statusno':
                                        urlsafe_base64_encode(force_bytes(
                                            "no")),
                                        'event_name':
                                        urlsafe_base64_encode(
                                            force_bytes(event.eventname)),
                                    }))),
                                             thread_id=user,
                                             thread_type=ThreadType.USER)
                            print("me too")
                            person.is_link_sended = True
                        else:
                            userid = person.facebook_address.rsplit('/',
                                                                    1).pop()
                            users = self.client.searchForUsers(userid)
                            print(users)
                            user = users[0]
                            print("User's ID: {}".format(user.uid))
                            print("User's name: {}".format(user.name))
                            print("User's profile picture URL: {}".format(
                                user.photo))
                            print("User's main URL: {}".format(user.url))
                            self.client.send(Message(text=strip_tags(
                                render_to_string(
                                    "eventinvitation.html", {
                                        'invitor':
                                        request.user.email,
                                        'attendee':
                                        person.name,
                                        'domain':
                                        get_current_site(request).domain,
                                        'event':
                                        event,
                                        'event_pk':
                                        urlsafe_base64_encode(
                                            force_bytes(event.pk)),
                                        'user_pk':
                                        urlsafe_base64_encode(
                                            force_bytes(person.pk)),
                                        'statusyes':
                                        urlsafe_base64_encode(
                                            force_bytes("yes")),
                                        'statusno':
                                        urlsafe_base64_encode(force_bytes(
                                            "no")),
                                        'event_name':
                                        urlsafe_base64_encode(
                                            force_bytes(event.eventname)),
                                    }))),
                                             thread_id=user.uid,
                                             thread_type=ThreadType.USER)
                        person.is_link_sended = True
                    except:
                        pass
                person.save()
Example #20
0
class PostImage:
    EVENT_FILE = './events.txt'
    PIC_DIR = './data'

    def __init__(self):
        self.client = self.fb_login()

    def fb_login(self):
        self.client = Client(FB_UN, FB_PW)
        return self.client

    def fb_logout(self):
        self.client.logout()

    def check_login_status(self):
        if not self.client.isLoggedIn():
            self.fb_login()

    def post_to_facebook(self):
        if len(os.listdir(self.PIC_DIR)) > 0:
            if len(os.listdir(self.PIC_DIR)) == 1:
                self.client.sendMessage(message=Message(
                    text='This is my last photo!!! Better restock me...'),
                                        thread_id=GROUP_CHAT_ID,
                                        thread_type=ThreadType.GROUP)
            random_pic = choice(os.listdir(self.PIC_DIR))
            file = os.path.abspath(f'{self.PIC_DIR}/{random_pic}')
            self.client.sendLocalImage(
                file,
                message=Message(text=', '.join((
                    str(random_pic).split('.')[0]).split('_'))),
                thread_id=GROUP_CHAT_ID,
                thread_type=ThreadType.GROUP)
            self.client.send(Message(
                text=f'I have {len(os.listdir(self.PIC_DIR))} photos left!'),
                             thread_id=GROUP_CHAT_ID,
                             thread_type=ThreadType.GROUP)
            os.remove(file)
        else:
            self.client.send(Message(
                text=
                'Hey you putz! I\'m out of pictures to send! Tell him to stock me up @Louis Kasser!'
            ),
                             thread_id=GROUP_CHAT_ID,
                             thread_type=ThreadType.GROUP)

    def check_if_should_post(self):
        with open(self.EVENT_FILE, 'r') as f:
            for line in f.readlines():
                if 'last_post' in line:
                    last_write_time = line.split('=')[1]
                    next_post_time = self.calc_time_elapsed(last_write_time)
                    if datetime.utcnow() >= next_post_time:
                        return True
                    else:
                        return False

    def calc_time_elapsed(self, last_write_time):
        next_post_time = parser.parse(last_write_time) + timedelta(hours=23,
                                                                   minutes=59)
        return next_post_time

    def write_last_post_time(self, new_time):
        with open(self.EVENT_FILE, 'w') as f:
            f.write(f'last_post={new_time}')
Example #21
0
"""
print ASCIIBomb		# just to give a cool look to terminal

class Help():
	def __init__(self):
		print("Script Help ")
	def BombingModeHelp(self):
		print("\nMode_1() will sent message to every user of client's friend list")
		print("\nMode_2() will send message to a certain victim")
		print("\nMode_3() will send message to a certain page")

username = input('\nPlease enter your username or email or mobile number :')
password = getpass.getpass()
client = Client('username','password')		#logging in

if client.isLoggedIn() is True:
	class FbBomber():
		
		def __init__(self):
			self.users = client.fetchAllUsers()	# All friends have fetched
			UserData = open("UserData.dat","w")	# UserData will preserve every user data
			for user in self.users:
				UserData.write("Name : ",user.name,"ID : ",user.uid)
			UserData.close()	# closing the file
		
		def Mode_1(self):
		# Mode_1() will sent message to every user of client's friend list
			for user in self.users:
				client.send(Message(text='Hi victim!'), thread_id=user.uid, thread_type=ThreadType.USER)
		
		def Mode_2(self,NameOfUser=client.name,MessageCount=1):
Example #22
0
from fbchat import Client
import fbchat

client1 = Client("Your Email or Phone", "Facebook Password")
#Logging into facebook
checklogin = client1.isLoggedIn()
#Login successfully return True
print(checklogin)
#o/p: True

####Find Top 5 users with same name with different User-Id
Tot_Users_with_same_name = client1.searchForUsers("Rajeev Kumar", 5)
for user in Tot_Users_with_same_name:
    print(user)
###o/p:
####<USER Rajeev Kumar (100003149965719)>
####<USER Rajeev Kumar (100002938065104)>
####<USER Rajeev Kumar (100001330735025)>
####<USER Rajeev Kumar (100003575685008)>
####<USER Rajeev Kumar (100003679172501)>

#Getting User name and Id of Rajeev Kumar
friends = client1.searchForUsers("Rajeev Kumar")
print(friends[0])
#o/p:<USER Rajeev Kumar (100003149965719)>

print(friends[0].uid)
#o/p:100003149965719

#Getting Fb User Id of Rajeev Kumar
uiid = friends[0].uid
Example #23
0
def send_msg(FirstName, Last_Name, GroupNames):

    encrypt.decrypt(dir_path + '/credentials/fbe')
    with open(dir_path + '/credentials/fbe', mode='rb') as f:
        content = f.read()
        content = base64.b64decode(content).decode('utf-8')

    username = str(content.split()[0])
    password = str(content.split()[1])

    client = Client(username, password)

    if client.isLoggedIn():

        # ---------------Person------------------
        name = FirstName + " " + Last_Name
        friends = client.searchForUsers(name)  # return a list of names
        friend = friends[0]
        msg = "Birthdays are a new start; fresh beginnings, a time to start new endeavours with new goals. Move forward with fresh confidence and courage. You are a special person, may you have an amazing today and year. Happy birthday " + FirstName

        # Will send the image located at `<image path>`
        client.sendRemoteImage(
            "https://images.unsplash.com/photo-1558636508-e0db3814bd1d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1950&q=80",
            thread_id=friend.uid,
            thread_type=ThreadType.USER,
        )
        client.send(Message(text=msg), thread_id=str(friend.uid), thread_type=ThreadType.USER)

        # -------------------------Group----------------------
        for GroupName in GroupNames:
            try:
                gname = GroupName
                groups = client.searchForGroups(gname)

                group = groups[0]
                client.sendRemoteImage(
                    "https://images.unsplash.com/photo-1558636508-e0db3814bd1d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1950&q=80",
                    thread_id=group.uid,
                    thread_type=ThreadType.GROUP,
                )
                client.send(Message(text=msg), thread_id=group.uid, thread_type=ThreadType.GROUP)
            except:
                continue

        client.logout()

    else:
        print('not logged in')



    #------------------------Automation using browser--------------------

    chrome_options = webdriver.ChromeOptions()

    prefs = {"profile.default_content_setting_values.notifications": 2}
    chrome_options.add_experimental_option("prefs", prefs)
    browser = webdriver.Chrome(dir_path + "/chromedriver")

    # open facebook.com using get() method
    browser.get('https://www.facebook.com/')

    # user_name or e-mail id
    username = username
    password = password


    element = browser.find_elements_by_xpath('//*[@id ="email"]')
    element[0].send_keys(username)


    element = browser.find_element_by_xpath('//*[@id ="pass"]')
    element.send_keys(password)


    # logging in
    log_in = browser.find_elements_by_id('loginbutton')
    log_in[0].click()


    browser.get('https://www.facebook.com/events/birthdays/')

    feed = 'Happy Birthday '

    element = browser.find_elements_by_xpath("//*[@class ='enter_submit\
    uiTextareaNoResize uiTextareaAutogrow uiStreamInlineTextarea \
        inlineReplyTextArea mentionsTextarea textInput']")

    cnt = 0

    for el in element:
        cnt += 1
        element_id = str(el.get_attribute('id'))
        XPATH = '//*[@id ="' + element_id + '"]'
        post_field = browser.find_element_by_xpath(XPATH)
        post_field.send_keys(feed)
        post_field.send_keys(Keys.RETURN)
        print("Birthday Wish posted for friend" + str(cnt))

    # Close the browser
    browser.close()

    encrypt.encrypt(dir_path + '/credentials/fbe')