Send facebook messages via SleekXMPP - python

I am trying to send a message on facebook chat with sleekXMPP, using the answer from here as a boilerplate: Send a Facebook Message with XMPP using Access Tokens in Python
My code is
import sleekxmpp
class SendMsgBot(sleekxmpp.ClientXMPP):
def init(self, jid, recipient, message):
print "..."
sleekxmpp.ClientXMPP.__init__(self, jid, 'ignore')
self.recipient = recipient
self.msg = message
self.add_event_handler("session_start", self.start, threaded=True)
def start(self, event):
self.send_presence()
self.get_roster()
self.send_message(mto=self.recipient, mbody=self.msg, mtype='chat')
self.disconnect(wait=True)
if __name__ == "__main__":
xmpp = SendMsgBot(from_id, to_id, unicode(message))
xmpp.credentials['apikey'] = api_key
xmpp.credentials['accesstoken'] = o_auth_token
if xmpp.connect(('chat.facebook.com', 5222)):
xmpp.process(block=True)
print("Done")
else:
print("Unable to connect")
However, when I run the script I get this error message:
Traceback (most recent call last):
File "sendMessagesScript.py", line 33, in <module>
xmpp = SendMsgBot(from_id, to_id, unicode(message))
File "/Library/Python/2.7/site-packages/sleekxmpp/clientxmpp.py", line 112, in __init__
self.register_plugin('feature_starttls')
File "/Library/Python/2.7/site-packages/sleekxmpp/basexmpp.py", line 264, in register_plugin
pconfig = self.plugin_config.get(plugin, {})
AttributeError: 'unicode' object has no attribute 'get'
Any ideas would be appreciated!

In the class SendMsgBot(sleekxmpp.ClientXMPP):, you need to change
def init(self, jid, recipient, message) to def __init__(self, jid, recipient, message)
I hope it will work.

Additionally, it seems that some important dashes have been ommitted from the original code.
I also had to change
xmpp.credentials['apikey'] = api_key
xmpp.credentials['accesstoken'] = o_auth_token
to
xmpp.credentials['api_key'] = api_key
xmpp.credentials['access_token'] = o_auth_token
These are apparently the parameter names that Facebook expects, as you can see in Facebook's PHP example

Related

ValueError: Port could not be cast to integer value as

Hy, I'm created a AmazonMQ using broker as RabbitMQ. Now I want to publish a message and read that message from the queue using python. So I followed the steps given in the AWS docs.
Link: Using Python Pika with Amazon MQ for RabbitMQ
I follow the same steps in docs but when I tried to send a message to the queue it gives me this error!
Traceback (most recent call last):
File "E:/Axcer/Using-Python-Pika-with-Amazon-MQ-for-RabbitMQ/publisher.py", line 26, in
basic_message_sender = BasicMessageSender(
File "E:\Axcer\Using-Python-Pika-with-Amazon-MQ-for-RabbitMQ\basicClient.py", line 15, in init
parameters = pika.URLParameters(url)
File "E:\Axcer\Using-Python-Pika-with-Amazon-MQ-for-RabbitMQ\Intern\lib\site-packages\pika\connection.py", line 757, in init
if parts.port is not None:
File "C:\Users\Yomal\Python38-32\lib\urllib\parse.py", line 174, in port
raise ValueError(message) from None
ValueError: Port could not be cast to integer value as 'xxxxxyyyy'
I have really no Idea about this issue! I hope that someone can help me with this. Thank you!
basicClient.py
import ssl
import pika
class BasicPikaClient:
def __init__(self, rabbitmq_broker_id, rabbitmq_user, rabbitmq_password, region):
# SSL Context for TLS configuration of Amazon MQ for RabbitMQ
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
ssl_context.set_ciphers('ECDHE+AESGCM:!ECDSA')
url = f"amqps://{rabbitmq_user}:{rabbitmq_password}#{rabbitmq_broker_id}.mq.{region}.amazonaws.com:5671"
parameters = pika.URLParameters(url)
parameters.ssl_options = pika.SSLOptions(context=ssl_context)
self.connection = pika.BlockingConnection(parameters)
self.channel = self.connection.channel()
publisher.py
from basicClient import BasicPikaClient
class BasicMessageSender(BasicPikaClient):
def declare_queue(self, queue_name):
print(f"Trying to declare queue({queue_name})...")
self.channel.queue_declare(queue=queue_name)
def send_message(self, exchange, routing_key, body):
channel = self.connection.channel()
channel.basic_publish(exchange=exchange,
routing_key=routing_key,
body=body)
print(f"Sent message. Exchange: {exchange}, Routing Key: {routing_key}, Body: {body}")
def close(self):
self.channel.close()
self.connection.close()
if __name__ == "__main__":
# Initialize Basic Message Sender which creates a connection
# and channel for sending messages.
basic_message_sender = BasicMessageSender(
"*******************",
"xxxxx",
"xxxxxyyyy#zzzzzzz",
"********"
)
# Declare a queue
basic_message_sender.declare_queue("hello world queue")
# Send a message to the queue.
basic_message_sender.send_message(exchange="", routing_key="hello world queue", body=b'Hello World!')
# Close connections.
basic_message_sender.close()

Sending screenshot

This is my code it should send me an email with a screenshot but instead I get the following error.
Traceback (most recent call last):
File "email_screenshot.py", line 34, in <module>
my_screenshot.start()
File "email_screenshot.py", line 26, in start
with open(im) as file:
TypeError: coercing to Unicode: need string or buffer, PngImageFile found
This is the code what should I do to get rid of the type error in this python2.7 code.
import pyscreenshot as ImageGrab
import smtplib
import base64
class Screenshot:
def __init__(self, email, password):
self.screenshot = ImageGrab.grab
self.email = email
self.password = password
def send_screenshot(self):
self.send_email(self.email, self.password, self.screenshot)
report = self.send_screenshot
report.start()
def send_email(self, email, password, message):
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(email, password)
server.sendmail(email, email, message)
server.quit()
def start(self):
im = ImageGrab.grab()
with open(im) as file:
file.write(base64.b64decode(im))
with im:
self.send_screenshot()
im.join()
my_screenshot = Screenshot("myuser", "mypass",)
my_screenshot.start()
does anyone have any ideas

Failing to open websocket connection to IBM Watson speech to text

The following code just returns the output: "Failed to open WebSocket" Please help me correct it. I suspect the ws_url might be faulty, but still unsure.
from ws4py.client.threadedclient import WebSocketClient
import base64, time
class SpeechToTextClient(WebSocketClient):
def __init__(self):
ws_url = "wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize"
username = "your username"
password = "your password"
auth_string = "%s:%s" % (username, password)
base64string = base64.b64encode(auth_string.encode())
try:
WebSocketClient.__init__(self, ws_url,
headers=[("Authorization", "Basic %s" % base64string)])
self.connect()
except: print("Failed to open WebSocket.")
def opened(self):
self.send('{"action": "start", "content-type": "audio/l16;rate=16000"}')
def received_message(self, message):
print(message)
stt_client = SpeechToTextClient()
time.sleep(3)
stt_client.close()
Error message is provided below:ยจ
Here is the full error message:
Traceback (most recent call last):
File "C:\Users\Vetle\Desktop\Python projects\problem.py", line 27, in
stt_client.close()
File "C:\Users\Vetle\AppData\Local\Programs\Python\Python35\lib\site-packages\ws4py\client__init__.py", line 205, in close
self._write(self.stream.close(code=code, reason=reason).single(mask=True))
File "C:\Users\Vetle\AppData\Local\Programs\Python\Python35\lib\site-packages\ws4py\websocket.py", line 283, in _write
raise RuntimeError("Cannot send on a terminated websocket")
RuntimeError: Cannot send on a terminated websocket
As per the API documentation you need to pass in an authentication token and not the basic service credentials. The Documentation has sample web socket code - https://www.ibm.com/watson/developercloud/speech-to-text/api/v1/#recognize_audio_websockets

AssertionError during idle_check in IMAPClient

I am attempting to have a python script that constantly monitors a gmail account for new emails. Using IMAPClient, it opens two imap connections, one in idle mode. Whenever a new message is received, the connection in idle mode tells the other connection that it should fetch new mail. The non-idle connection will fetch the mail, perform some processing, then archive the email.
The problem comes when I have many emails arriving in a short period of time, more than a few in a minute. In this case, I get an AssertionError. Below is a minimal example to reproduce the error. In addition to the imap connection, it also opens an smtp connection so that it can send the emails to itself. It will usually fail with the AssertionError at some point after 5-7 emails have been sent. The AssertionError comes in the call to idle_check.
A few short comments on running the code. It does not use OAuth, and so gmail's must be set to allow less secure apps. The "username" and "password" fields at the bottom of the script must be set. The script will also archive any emails that are currently in the inbox, and so it should not be run on a primary email account.
#!/usr/bin/env python3
import smtplib
import imapclient
import email
import threading
import time
class Server(object):
def __init__(self,username,password):
self.username = username
self.password = password
def start(self):
self.stop_running = threading.Event()
self.has_mail = threading.Event()
threading.Thread(target=self._idle).start()
threading.Thread(target=self._poll).start()
print('Listening for messages now')
def _idle(self):
imap_idle = self.imap_connect()
while not self.stop_running.is_set():
imap_idle.idle()
for i in range(600):
try:
if imap_idle.idle_check(1):
self.has_mail.set()
except AssertionError as e:
self.stop_running.set()
raise
imap_idle.idle_done()
imap_idle.noop()
def _poll(self):
imap_poll = self.imap_connect()
self.process_unread(imap_poll)
while True:
if self.has_mail.wait(1):
self.has_mail.clear()
self.process_unread(imap_poll)
if self.stop_running.is_set():
return
def imap_connect(self):
imap = imapclient.IMAPClient('imap.gmail.com',use_uid=True,ssl=True)
imap.login(self.username,self.password)
imap.select_folder('INBOX')
return imap
def process_unread(self, imap):
imap.select_folder('INBOX')
messages = imap.search()
if messages:
imap.copy(messages,'[Gmail]/All Mail')
imap.delete_messages(messages)
def smtp_connect(self):
smtp = smtplib.SMTP('smtp.gmail.com',587)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(self.username,self.password)
return smtp
def send(self,recipient,subject='',body=''):
headers = ['from: ' + self.username,
'subject: ' + subject,
'to: ' + recipient,
'mime-version: 1.0',
'content-type: text/html']
headers = '\r\n'.join(headers)
self.smtp_connect().sendmail(self.username,recipient,headers+'\r\n\r\n'+body)
def main():
username = 'username#gmail.com'
password = 'password'
s = Server(username, password)
s.start()
for i in range(8):
if s.stop_running.is_set():
break
print('Sending message',i)
s.send(username,
'Test Message'.format(i),
'Body {}'.format(i))
time.sleep(15)
if __name__=='__main__':
main()
The error messsage given is as follows. The text variable at the time of error is sometimes b'XISTS' and sometimes b' FLAGS (\\Seen))'.
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.4/threading.py", line 920, in _bootstrap_inner
self.run()
File "/usr/lib/python3.4/threading.py", line 868, in run
self._target(*self._args, **self._kwargs)
File "./emailer.py", line 31, in _idle
if imap_idle.idle_check(1):
File "/path/to/the/venv/lib/python3.4/site-packages/imapclient/imapclient.py", line 519, in idle_check
resps.append(_parse_untagged_response(line))
File "/path/to/the/venv/lib/python3.4/site-packages/imapclient/imapclient.py", line 1093, in _parse_untagged_response
assert text.startswith(b'* ')
AssertionError
I am running this with Python 3.4.0, using IMAPClient 0.13. This is being run in a clean virtualenv, with no other libraries installed. Any assistance would be quite appreciated.

Twisted - SleekXMPP compatibility

I am making a XMPP middleware in python which listens on a an address(host,port) and when it receives some connection on that port, it sends a XMPP message to a jid(XMPP user) on a server.
A quick review of my setup
For networking part I am using twisted
For XMPP - SleekXMPP
XMPP server - Openfire
Now when I tried using sleekXMPP without importing anything from twistedm it was working fine.
However I i try to mix sleekXMPP and twisted in one program (by importing them) I get the follwing error.
Traceback (most recent call last):
File "sleekXMPP/prog_3.py", line 124, in <module>
main()
File "sleekXMPP/prog_3.py", line 111, in main
xmppThread = ClientThread(dir_q)
File "sleekXMPP/prog_3.py", line 41, in __init__
self.xmpp = xmppClient(self.jid, self.password)
File "sleekXMPP/prog_3.py", line 17, in __init__
sleekxmpp.ClientXMPP.__init__(self, jid, password)
File "build\bdist.win32\egg\sleekxmpp\clientxmpp.py", line 65, in __init__
File "build\bdist.win32\egg\sleekxmpp\basexmpp.py", line 72, in __init__
File "build\bdist.win32\egg\sleekxmpp\jid.py", line 461, in __init__
File "build\bdist.win32\egg\sleekxmpp\jid.py", line 150, in _parse_jid
File "build\bdist.win32\egg\sleekxmpp\jid.py", line 202, in _validate_domain
File "C:\Python27\lib\site-packages\twisted-12.2.0-py2.7-win32.egg\twisted\python \compat.py", line 22, in inet_pton
raise ValueError("Illegal characters: %r" % (''.join(x),))
ValueError: Illegal characters: u't'
The code is as follows:
import sleekxmpp
import ssl
import Queue
import threading
import time
import logging
import traceback
import sys
from twisted.internet import reactor, protocol , endpoints
class xmppClient(sleekxmpp.ClientXMPP):
"""
This class defines the xmppClient object used to interact with the XMPP server
"""
def __init__(self, jid, password):
# the constructor
sleekxmpp.ClientXMPP.__init__(self, jid, password)
self.add_event_handler('session_start', self.start)
def start(self, event):
self.send_presence()
self.get_roster()
def send_note(self):
self.mssg = r"Hello from XMPP Service"
self.recipient = r"testuser2#ghost"
self.send_message(mto=self.recipient,
mbody=self.mssg,
mtype='chat')
print "Message sent"
class ClientThread(threading.Thread):
def __init__(self, dir_q):
super(ClientThread, self).__init__()
self.dir_q = dir_q
self.stoprequest = threading.Event()
self.jid = 'testuser1#ghost'
self.password = 'password'
self.xmpp = xmppClient(self.jid, self.password)
self.xmpp.register_plugin('xep_0030') # Service Discovery
self.xmpp.register_plugin('xep_0004') # Data Forms
self.xmpp.register_plugin('xep_0060') # PubSub
self.xmpp.register_plugin('xep_0199') # XMPP Ping
self.xmpp.ssl_version = ssl.PROTOCOL_SSLv3
if self.xmpp.connect():
print("Connected")
self.xmpp.process(block=False)
else:
print("Unable to connect.")
def run(self):
while not self.stoprequest.isSet():
try:
req = self.dir_q.get(True, 0.05)
if req == 1:
self.xmpp.send_note()
except Queue.Empty:
continue
def join(self, timeout=None):
self.stoprequest.set()
super(ClientThread, self).join(timeout)
class reqSimulator(threading.Thread):
def __init__(self, dir_q):
super(reqSimulator, self).__init__()
self.dir_q = dir_q
def run(self):
while(1):
self.dir_q.put(1)
time.sleep(0.5)
"""class sendProtocol(protocol.Protocol):
def connectionMade(self):
r = reqSimulator(self.factory.dir_q)
r.run()
def connectionLost(self, reason):
pass
def dataReceived(self, data):
self.transport.loseConnection()"""
def main():
logging.basicConfig()
dir_q = Queue.Queue()
xmppThread = ClientThread(dir_q)
xmppThread.start()
sim = reqSimulator(dir_q)
"""factory = protocol.ServerFactory()
factory.dir_q = dir_q
factory.protocol = sendProtocol
endpoints.serverFromString(reactor, "tcp:8001").listen(factory)
reactor.run()
"""
sim.start()
if __name__ == "__main__":
main()
Note that in this code, the actual networking code is commented and I am using a reqSimulator class to simulate the oncoming requests.
I tried to google for any issued but got no result. Does anybody have an idea what is wrong here?
This is due to the fact that Twisted implements inet_pton for Windows, but uses different exceptions for failures than the stdlib version.
I've fixed Sleek on github for this (master and develop branches), and there will be a new point release for it shortly.

Categories