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
Related
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()
I'm making a simple python chatroom type server, and I am trying to implement server commands. Sending and receiving messages work fine but for some reason when I send a server command It gets received weird. I assume it's how the message is being sent that's causing it to act weird because the server sends server commands separately from how it sends regular messages. Here are the snippets that I think are the problem:
SERVER SIDE:
userData = "server".encode("utf-8")
userHeader = f"{len(userData):<{HEADER_LENGTH}}".encode("utf-8")
print(userHeader)
command = str(command)
messageData = f"cmd${command}".encode("utf-8")
messageHeader = f"{len(command):< {HEADER_LENGTH}}".encode("utf-8")
for client_socket in self.clients:
client_socket.send(userHeader + userData + messageHeader + messageData)
window.logData(f"sent server command {command}")
window.logChat("SERVER",command)
This gets called when a button is pressed and then some input is passed in as the command
Here's how the client receives data:
while True:
try:
username_header = self.client_socket.recv(HEADER_LENGTH)
if(not len(username_header)):
print("connection closed by server")
sys.exit()
print(username_header.decode("utf-8").strip())
username_length = int(username_header.decode("utf-8").strip())
username = self.client_socket.recv(username_lenght).decode("utf-8")
message_header = self.client_socket.recv(HEADER_LENGTH)
message_length = int(message_header.decode("utf-8").strip())
messageRaw = self.client_socket.recv(message_length).decode("utf-8")
type_, message = messageRaw.split("$")
if(type_ == "message"):
GUI.outgoing.insert(END, "")
GUI.incoming.insert(END, f"{username} >> {message}")
elif(type_ == "cmd"):
if(username == "sever"):
print("recieved server command")
except IOError as e:
if(e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK):
print("READ ERR",str(e))
sys.exit()
continue
I'm not getting any errors on the server side but I am on the client side so here's the output:
6
TEST
Exception in thread Thread-1:
Traceback (most recent call last):
File "/home/kali/anaconda3/lib/python3.7/threading.py", line 926, in _bootstrap_inner
self.run()
File "/home/kali/anaconda3/lib/python3.7/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "client.py", line 119, in main
username_lenght = int(username_header.decode("utf-8").strip())
ValueError: invalid literal for int() with base 10: 'TEST'
I'm sending the text "TEST" to see if the server is receiving data, where it prints the length of the username header it prints 6 which is the length "SERVER" but it also prints "TEST" which is where everything goes wrong.
If you want to play around with the code the github page is https://github.com/snakebite-382/Chatty.py/tree/unstable make sure you download the scripts from the unstable branch. The stable branch has the first release which doesn't have a GUI or the ability to send server commands.
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.
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
I am writing a program that sends an email using Python. What I have learned from various forums is the following piece of code:
#!/usr/bin/env python
import smtplib
sender = "sachinites#gmail.com"
receivers = ["abhisheks#cse.iitb.ac.in"]
yourname = "Abhishek Sagar"
recvname = "receptionist"
sub = "Testing email"
body = "who cares"
message = "From: " + yourname + "\n"
message = message + "To: " + recvname + "\n"
message = message + "Subject: " + sub + "\n"
message = message + body
try:
print "Sending email to " + recvname + "...",
server = smtplib.SMTP('smtp.gmail.com:587')
username = 'XYZ#gmail.com'
password = '*****'
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(sender, receivers, message)
server.quit()
print "successfully sent!"
except Exception:
print "Error: unable to send email"
But it is simply printing ""Error: unable to send email" and exits out on the terminal. How might I resolve this?
I modified the last two lines to
except Exception, error:
print "Unable to send e-mail: '%s'." % str(error)
I get the following error message :
Traceback (most recent call last):
File "./2.py", line 45, in <module>
smtpObj = smtplib.SMTP('localhost')
File "/usr/lib/python2.6/smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.6/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.6/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/usr/lib/python2.6/socket.py", line 514, in create_connection
raise error, msg
socket.error: [Errno 111] Connection refused
If message headers, payload contain non-ascii characters then they should be encoded:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from email.header import Header
from email.mime.text import MIMEText
from getpass import getpass
from smtplib import SMTP_SSL
login, password = 'user#gmail.com', getpass('Gmail password:')
recipients = [login]
# create message
msg = MIMEText('message body…', 'plain', 'utf-8')
msg['Subject'] = Header('subject…', 'utf-8')
msg['From'] = login
msg['To'] = ", ".join(recipients)
# send it via gmail
s = SMTP_SSL('smtp.gmail.com', 465, timeout=10)
s.set_debuglevel(1)
try:
s.login(login, password)
s.sendmail(msg['From'], recipients, msg.as_string())
finally:
s.quit()
If you print the error message, you will likely get a comprehensive description of what error occurred. Try (no pun intended) this:
try:
# ...
except Exception, error:
print "Unable to send e-mail: '%s'." % str(error)
If, after reading the error message, you still do not understand your error, please update your question with the error message and we can help you some more.
Update after additional information:
the error message
socket.error: [Errno 111] Connection refused
means the remote end (e.g. the GMail SMTP server) is refusing the network connection. If you take a look at the smtplib.SMTP constructor, it seems you should change
server = smtplib.SMTP('smtp.gmail.com:587')
to the following.
server = smtplib.SMTP(host='smtp.gmail.com', port=587)
According to the error message, you use the localhost as the SMTP server, then the connection was refused. Your localhost didn't have an SMTP sever running I guess, you need to make sure the SMTP server you connect is valid.