Python Facebookchat AttributeError 'str' object has no attribute '_to_send_data' - python-3.x

I was trying send message to my friend using python.
But I am getting this error.
sent = client.send(friend.uid, msg)
File "/home/can/anaconda3/lib/python3.7/site-packages/fbchat/_client.py", line 1059, in send
data.update(message._to_send_data())
AttributeError: 'str' object has no attribute '_to_send_data'
I can login in to my account and ı can enter value of friends also ı can enter my friend name.
Then when ı write my message for example "hello" then press enter, it gives me error.
Codes of program;
import fbchat
from getpass import getpass
username = str(input("Username: "))
client = fbchat.Client(username, getpass())
no_of_friends = int(input("Number of friends: "))
for i in range(no_of_friends):
name = str(input("Name: "))
friends = client.searchForUsers(name) # return a list of names
friend = friends[0]
msg = str(input("Message: "))
sent = client.send(friend.uid, msg)
if sent:
print("Message sent successfully!")
can I see "Message sent successfully!" this message? also modules are successfully installed.
I am working on Ubuntu 19.10

I fix my issue by myself. ı put the answer here maybe someone will have same error and can find the answer here.
My mistake is here;
sent = client.send(friend.uid, msg)
I changed like this one;
sent = client.sendMessage(msg, thread_id=friend.uid)
and it's worked!

Related

UnicodePython 3: EncodeError: 'ascii' codec can't encode character '\xe4'

I am trying to send some emails with pandas from an excel-file.
I have this error for over a week now and even after hours of searching through SO, google, forums and so on, I just can't come u with an answer to fix the problem.
Here is the code:
import pandas as pd
import smtplib
your_name = "myname"
your_email = "mymail"
your_password = "mypw"
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(your_email, your_password)
# Read the file
email_list = pd.read_excel("myfile.xlsx")
# Get all the Names, Email Addreses, Subjects and Messages
all_emails = email_list['Email']
all_messages = email_list['Text']
# Loop through the emails
for idx in range(len(all_emails)):
# Get each records name, email, subject and message
email = all_emails[idx]
message = all_messages[idx]
# Create the email to send
full_email = ("From: {0} <{1}>\n"
"To: <{2}>\n"
"Subject: My_Subject_Title\n\n"
"{3}"
.format(your_name, your_email, email, message))
# In the email field, you can add multiple other emails if you want
# all of them to receive the same text
try:
server.sendmail(your_email, [email], full_email)
print('Email to {} successfully sent!\n\n'.format(email))
except Exception as e:
print('Email to {} could not be sent :( because {}\n\n'.format(email, str(e)))
server.close()
I am getting the error:
'ascii' codec can't encode character '\xe4'
So obviously the error is caused by some european letters inside my excel file.
What I tryied (along several others ways) was to encode the file:
email_list = pd.read_excel("myfile.xlsx", encoding=("utf-8"))
>>> TypeError: read_excel() got an unexpected keyword argument 'encoding'
or:
email_list = pd.read_excel("myfile.xlsx")
email_list.encode("utf-8")
>>> AttributeError: 'DataFrame' object has no attribute 'encode'
Non if it seems to work.
I'm happy if someone can help me out in what I`m doing wrong.
Very new to python and these are my first real trys to implement some actual work-related problems.
Thanks a lot in advance!

Python IMAP TypeError: 'Nonetype' Object Is Not Subscriptable

I am using imap to check for unread emails that match a specific subject. When I receive an email from my test email, it goes just fine, but when it comes from an automatic system that I'm needing it to check the emails from, I get an error stating that 'Nonetype' object is not subscriptable. The following is my code:
import imaplib, time, email, mailbox, datetime
server = "imap.gmail.com"
port = 993
user = "Redacted"
password = "Redacted"
def main():
while True:
conn = imaplib.IMAP4_SSL(server, port)
conn.login(user, password)
conn.list()
conn.select('inbox', readonly=True)
result, data = conn.search(None, '(UNSEEN SUBJECT "Alert: Storage Almost At Max Capacity")')
i = len(data[0].split())
for x in range (i):
latest_email_uid = data[0].split()[x]
result, email_data = conn.uid('fetch', latest_email_uid, '(RFC822)')
raw_email = email_data[0][1] #This is where it throws the error
raw_email_string = raw_email.decode('utf-8')
email_message = email.message_from_string(raw_email_string)
date_tuple = email.utils.parsedate_tz(email_message['Date'])
local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))
local_message_date = "%s" %(str(local_date.strftime("%a, %d %b %Y %H:%M:%S")))
for part in email_message.walk():
if part.get_content_type() == "text/plain":
body = part.get_payload(decode=True)
body = body.decode('utf-8')
body = body.split()
#Do some stuff
conn.close()
if __name__ == "__main__":
main()
And the following is the traceback:
Traceback (most recent call last):
File "TestEmail.py", line 200, in <module>
main()
File "TestEmail.py", line 168, in main
raw_email = email_data[0][1]
TypeError: 'NoneType' object is not subscriptable.
I don't understand why this would work in an email sent from a person's email, yet not work when my system emails me an alert. Is there any obvious fix to this?
EDIT: I've tried printing the result and email variables. The following was their output:
Result: OK
Email: [None]
Whereas if I test the script against an email with the same subject, but sent from my test email, result is still "OK", but an email is contained.
EDIT#2: I've noticed that the format of the emails are a little different. The one that is being received fine is both text/plain and text/html, whereas the one that isn't being accepted is text/plain with Content-Transfer-Encoding: 7-bit. How might I remedy this? If I forward the email through a filter and check the email receiving from the filter, my code works just fine. However, I would like to not have to use multiple emails for this.
You are searching for message sequence numbers, and fetching by uid.
If you are going to use conn.uid('fetch'), you must also use conn.uid('search'), otherwise you are searching for apples and fetching oranges.
Thus, since not all MSNs are UIDs, you are occasionally fetching non-existent messages, which is not an error, but it just won't return you anything.

How to call any other event in the Slack API besides [message]?

I'm playing around with trying to make a bot in the slack channel so that I can understand how the whole process works. I have 2 questions. [1st question solved]First, I know how to send a message if someone said anything but I can't figure out how to check what was specifically said. Here's my code:
import os
import time
from slackclient import SlackClient
BOT_TOKEN = os.getenv('SLACK_BOT_USER_TOKEN')
print(BOT_TOKEN)
CH_NM = "bot_testing"
def main():
sc = SlackClient(BOT_TOKEN)
SM = sc.rtm_send_message
if sc.rtm_connect():
print("Bot running")
SM(CH_NM, "Started")
while True:
for slack_message in sc.rtm_read():
message = slack_message.get("text")
user = slack_message.get("user")
if 'hello' in message:
SM(CH_NM, "Hey, <#{}>!".format(user))
if not message or not user:
continue
SM(CH_NM, """<#{}> wrote something...""".format(user))
time.sleep(.5)
if __name__ == '__main__':
main()
The main line I'm having trouble with is
if 'hello' in message:
SM(CH_NM, "Hey, <#{}>!".format(user))
because I can't iterate through 'message' since it is 'NoneType'. How then would I go about checking if it contained a specific string?
Second question, I see that there are all sorts of event types, but mine only seems to work for the "message" type of events. If I wanted to return something every time a specific user started typing for example what would I add to make that work? I already tried adding typing = slack_message.get("user_typing") but understandably it doesn't work since 'user_typing' is an event type, not part of the message event type I'm pulling 'text' and 'user' out of.
So you know, I'm using python 3.6, Windows 10, powershell.
The issue was that I had my if not message or not user: continue line below the if 'hello' in message: line, so it would error out due to any other event that is happening that isn't a message. 1st Issue solved.

authenticating gmail atom feed to return message count in 'PYTHON 3' [duplicate]

Gmail has this sweet thing going on to get an atom feed:
def gmail_url(user, pwd):
return "https://"+str(user)+":"+str(pwd)+"#gmail.google.com/gmail/feed/atom"
Now when you do this in a browser, it authenticates and forwards you. But in Python, at least what I'm trying, isn't working right.
url = gmail_url(settings.USER, settings.PASS)
print url
opener = urllib.FancyURLopener()
f = opener.open(url)
print f.read()
Instead of forwarding correctly, it's doing this:
>>>
https://user:pass#gmail.google.com/gmail/feed/atom
Enter username for New mail feed at mail.google.com:
This is BAD! I shouldn't have to type in the username and password again!! How can I make it just auto-forward in python as it does in my web browser, so I can get the feed contents without all the BS?
You can use the HTTPBasicAuthHandler, I tried the following and it worked:
import urllib2
def get_unread_msgs(user, passwd):
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(
realm='New mail feed',
uri='https://mail.google.com',
user='%s#gmail.com' % user,
passwd=passwd
)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
feed = urllib2.urlopen('https://mail.google.com/mail/feed/atom')
return feed.read()

In this context, is there anyway I can use requests.post() without also using BeautifulSoup?

I've spent the day day and-a-half (I'm a beginner) trying to work out how to do something simple: Fill in an ID code and hit 'search'. I've read the requests docs and scoured stack overflow for examples, but none seem to help me.
What I want to do is run through a list of IDs that I have and check off which one's are valid and which are invalid. (This is for academic research)
Here's my code:
import requests
url = 'https://ndber.seai.ie/pass/ber/search.aspx'
payload = {'ctl00$DefaultContent$BERSearch$dfSearch$txtBERNumber':'100000000'
}
#the above dictionary key corresponds to the name , found using Firefox inspector in the source code.
#I have tried using input ID too with no difference in outcome
#enter in arbitrary number of '100000000'- expect to see 'Invalid ID Number' printed
r = requests.post(url, data = payload)
print(r.status_code, r.reason)
print(r.text)
if 'Number.'in r.text: #'Number' is an arbitrary word that happens to be in the page if a correct ID code is entered
print('Valid ID Number')
elif 'No results found.' in r.text: #as above, 'No results found' is in the page if an incorrect ID is entered
print('Invalid ID Number') #with the aboove number entered, I would expect this line to be printed
else:
print('Code Failure') #this line gets printed
I've tried to comment it as much as possible, so you can see what I'm at.
The output I get is Code Failure
The reason why BeautifulSoup comes into all this is because I asked for help on Reddit's excellent 'learn python' subreddit yesterday. A Redditor generously took the time to try to explain where I went wrong and what I should do differently. Here's what (s)he suggested I do:
enter image description here, which involves BS4.
So, is the Redditor right, or can this be done in a simple and 'light' way using the requests library?
Cheers!
Make sure to simulate exact same post with parameters, you can use firefox's firebug to see what parameters are beeing sent.
Below you can see the parameters, I've seen.
__EVENTARGUMENT=
__EVENTTARGET=
__EVENTVALIDATION=/wEdAAUFK13s0OHvBcOmXYSKCCYAA5nYY19nD30S2PPC/bgb6yltaY6CwJw6+g9S5X73j5ccPYOXbBJVHSWhVCIjHWYlwa4c5fa9Qdw0vorP2Y9f7xVxOMmbQICW5xMXXERtE7U18lHqXqDZVqJ8R/A9h66g
__SCROLLPOSITIONX=0
__SCROLLPOSITIONY=114
__VIEWSTATE=/wEPDwULLTE2MDEwODU4NjAPFgIeE1ZhbGlkYXRlUmVxdWVzdE1vZGUCARYCZg9kFgICAw9kFgICAw8WAh4FY2xhc3MFC21haW53cmFwcGVyFgQCBQ8PFgIeB1Zpc2libGVnZGQCCQ9kFgICAQ9kFgxmD2QWAgIBD2QWAgIBD2QWAmYPZBYCZg9kFgQCAQ8WAh4JaW5uZXJodG1sZWQCAw9kFgICAg9kFgJmD2QWBAIBD2QWAgIDDw8WCh4EXyFTQgKAAh4MRGVmYXVsdFdpZHRoHB4EVGV4dAUFY3RsMDAeB1Rvb2xUaXAFPlBsZWFzZSBlbnRlciBhIHZhbHVlLCB3aXRoIG5vIHNwZWNpYWwgY2hhcmFjdGVycywgd2l0aCBubyB0ZXh0HgVXaWR0aBxkZAIDD2QWAgIDDw8WCh8EAoACHwUcHwYFCTEwMDAwMDAwMB8HBT5QbGVhc2UgZW50ZXIgYSB2YWx1ZSwgd2l0aCBubyBzcGVjaWFsIGNoYXJhY3RlcnMsIHdpdGggbm8gdGV4dB8IHGRkAgQPFCsAAmQQFgAWABYAFgJmD2QWAgICD2QWAmYPPCsAEQIBEBYAFgAWAAwUKwAAZAIGDxYCHwJoFgQCAQ8WAh8CaGQCAw9kFgJmD2QWAmYPZBYCAgMPZBYCZg9kFgJmD2QWAgIBDxYCHwJoZAIIDxYCHwJoFgQCAQ8WAh8CaGQCAw9kFgJmD2QWAmYPZBYCAgMPZBYCZg9kFgJmD2QWAgIBDxYCHwJoZAIKDxYCHwJoFgQCAQ8WAh8CaGQCAw9kFgJmD2QWAmYPZBYCAgMPZBYCZg9kFgJmD2QWAgIBDxYCHwJoZAIMDxYCHwJoFgQCAQ8WAh8CaGQCAw9kFgJmD2QWAmYPZBYCAgMPZBYCZg9kFgJmD2QWAgIBDxYCHwJoZBgBBTNjdGwwMCREZWZhdWx0Q29udGVudCRCRVJTZWFyY2gkZ3JpZFJhdGluZ3MkZ3JpZHZpZXcPZ2QPHVcTs3MrN3SZqli/KiHgWASd1DRvCLPuS7Rs+GRQAQ==
__VIEWSTATEGENERATOR=1F9CCB97
ctl00$DefaultContent$BERSearch$dfSearch$Bottomsearch=Search
ctl00$DefaultContent$BERSearch$dfSearch$txtBERNumber=2313131
ctl00$DefaultContent$BERSearch$dfSearch$txtMPRN=11111111111
And belowe code just worked,
from __future__ import unicode_literals
import requests
url = 'https://ndber.seai.ie/pass/ber/search.aspx'
payload = {'__EVENTVALIDATION':'/wEdAAUFK13s0OHvBcOmXYSKCCYAA5nYY19nD30S2PPC/bgb6yltaY6CwJw6+g9S5X73j5ccPYOXbBJVHSWhVCIjHWYlwa4c5fa9Qdw0vorP2Y9f7xVxOMmbQICW5xMXXERtE7U18lHqXqDZVqJ8R/A9h66g',
'__VIEWSTATE':'/wEPDwULLTE2MDEwODU4NjAPFgIeE1ZhbGlkYXRlUmVx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F9CCB97',
'ctl00$DefaultContent$BERSearch$dfSearch$Bottomsearch':'Search',
'ctl00$DefaultContent$BERSearch$dfSearch$txtBERNumber':'2313131',
'ctl00$DefaultContent$BERSearch$dfSearch$txtMPRN':'11111111111'
}
session = requests.session()
r = requests.post(url, data=payload)
if 'Number.'in r.text: #'Number' is an arbitrary word that happens to be in the page if a correct ID code is entered
print('Valid ID Number')
elif 'No results found.' in r.text: #as above, 'No results found' is in the page if an incorrect ID is entered
print('Invalid ID Number') #with the aboove number entered, I would expect this line to be printed
else:
print('Code Failure') #this line gets printed"""
Just put your parameters in the payload dictionary, rest of the parameters can stay they I think
BER/DEC Number > ctl00$DefaultContent$BERSearch$dfSearch$txtBERNumber
MPRN > ctl00$DefaultContent$BERSearch$dfSearch$txtMPRN

Resources