Python pexpect.expect() on Telegram CLI - python

I'm trying to make a bot for Telegram on my RPi but I'm pretty new to this. I installed Telegram Cli and pexpect.
This is my test.py file:
import pexpect
telegram = pexpect.spawn('./telegram -k tg.pub')
telegram.expect("User")
telegram.send("msg Big_Boss test")
However this give me the following error:
Traceback (most recent call last):
File "test.py", line 5, in <module>
telegram.expect("User*")
File "/usr/local/lib/python2.7/dist-packages/pexpect/__init__.py", line 1451, in expect
timeout, searchwindowsize)
File "/usr/local/lib/python2.7/dist-packages/pexpect/__init__.py", line 1466, in expect_list
timeout, searchwindowsize)
File "/usr/local/lib/python2.7/dist-packages/pexpect/__init__.py", line 1554, in expect_loop
raise EOF(str(err) + '\n' + str(self))
pexpect.EOF: End Of File (EOF). Exception style platform.
I couldnt find any good documentation about the expect function. Basically what I am trying to do is send X when someone messages me something containing Y. But I can't get the first thing working. Simply sending a command.

Here's a Pexpect tutorial, and some sample code:
source
import pexpect
calc = pexpect.spawn('bc')
calc.expect("details")
print calc.send("1+2")
output
3

Related

Python script runs correctly in terminal gives error when run via crontab

I have written a short python script that uses bleak and asyncio to control a bluetooth LE device. The script works exactly as intended when I run it manually in pycharm or terminal, however I want to run it at specific intervals using crontab.
I've searched for a solution and tried adding absolute paths as well as logging errors. I have found that the script throws an error when run from crontab but I don't quite understand how to fix it.
Here is the script:
#!/usr/bin/python
from bleak import BleakClient
import asyncio
address = "DFB18A2C-6BAB-439E-AF05-485FB4259B75"
MODEL_NBR_UUID = "99FA0002-338A-1024-8A49-009C0215F78A"
async def main(address):
async with BleakClient(address) as client:
for i in range(3):
await client.write_gatt_char(MODEL_NBR_UUID, bytes.fromhex("0800"))
time.sleep(0.5)
asyncio.run(main(address))
And here is the error from crontab log:
Traceback (most recent call last):
File "/Users/emileberhard/PycharmProjects/BedMove/main.py", line 19, in <module>
asyncio.run(main(address))
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
return future.result()
File "/Users/emileberhard/PycharmProjects/BedMove/main.py", line 13, in main
async with BleakClient(address) as client:
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/bleak/backends/client.py", line 61, in __aenter__
await self.connect()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/bleak/backends/corebluetooth/client.py", line 78, in connect
device = await BleakScannerCoreBluetooth.find_device_by_address(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/bleak/backends/scanner.py", line 220, in find_device_by_address
return await cls.find_device_by_filter(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/bleak/backends/scanner.py", line 249, in find_device_by_filter
async with cls(detection_callback=apply_filter, **kwargs):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/bleak/backends/corebluetooth/scanner.py", line 44, in __init__
self._manager = CentralManagerDelegate.alloc().init()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/bleak/backends/corebluetooth/CentralManagerDelegate.py", line 88, in init
raise BleakError("Bluetooth device is turned off")
bleak.exc.BleakError: Bluetooth device is turned off
Exception ignored in: <CentralManagerDelegate objective-c instance 0x0>
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/bleak/backends/corebluetooth/CentralManagerDelegate.py", line 102, in __del__
IndexError: NSRangeException - Cannot remove an observer <CentralManagerDelegate 0x7fd036fbe0b0> for the key path "isScanning" from <CBCentralManager 0x600000aab100> because it is not registered as an observer.
Exception ignored in: <function CentralManagerDelegate.__del__ at 0x7fd01863cca0>
I'm running MacOS btw!
Thanks in advance!
remove that command from your cronjob.
do this, select your editor of choice from the list.
sudo crontab -e
then add your cronjob, exit and then save (these will run as root)
0 0 * * * /usr/local/bin/python3.9 /users/emileberhard/PycharmProjects/BedMove/main.py >> /users/emileberhard/out2.txt 2>&1
This happens when you have bluetooth off on your OSX device.

VI_ERROR_TMO (-1073807339) on Anritsu OSA

I'm working on interfacing an old Optical Spectrum Analyzer Anritsu MS9710B with a RS232 connection. A year ago, I managed to comunicate with him, send SCPI command using pyvisa and receive data. Today, I execute the exact same code with libraries up to date and I get an error Timeout when I query IDN or anything. The RS232-USB drivers are ok, I manage to open a communication but a query or read fail.
I changed the parameter to "RS232C" on the OSA parameters and my communication parameters are the same between OSA and program. Following advices from the forum, I tried the connection with NI-VISA where I get the same error. I tried to change timeout parameter, write_termination and read_termination but there isn't any change. The manual is very hard to understand termination value, but when it worked I didn't add anything.
I don't know anymore what to do.
Any advices and help would be warmly welcome to fix my problem !
import pyvisa
from pyvisa.constants import StopBits, Parity
rm = pyvisa.ResourceManager()
print(rm.list_resources())
my_instrument = rm.open_resource('ASRL5::INSTR')
my_instrument.baud_rate=9600
my_instrument.data_bits=8
my_instrument.parity=Parity.even
my_instrument.stop_bits=StopBits.one
my_instrument.write('*IDN?')
print(my_instrument.read())```
'''
('ASRL5::INSTR',)
Traceback (most recent call last):
File "PremiereComm.py", line 26, in <module>
print(my_instrument.read())
File "C:\Program Files\Python38\lib\site-packages\pyvisa\resources\messagebased.py", line 486, in read
message = self._read_raw().decode(enco)
File "C:\Program Files\Python38\lib\site-packages\pyvisa\resources\messagebased.py", line 442, in _read_raw
chunk, status = self.visalib.read(self.session, size)
File "C:\Program Files\Python38\lib\site-packages\pyvisa\ctwrapper\functions.py", line 2337, in read
ret = library.viRead(session, buffer, count, byref(return_count))
File "C:\Program Files\Python38\lib\site-packages\pyvisa\ctwrapper\highlevel.py", line 222, in _return_handler
return self.handle_return_value(session, ret_value) # type: ignore
File "C:\Program Files\Python38\lib\site-packages\pyvisa\highlevel.py", line 251, in handle_return_value
raise errors.VisaIOError(rv)
pyvisa.errors.VisaIOError: VI_ERROR_TMO (-1073807339): Timeout expired before operation completed.
>>> '''

python skype groupchat GET response error

I'm getting error in trying to communicate in a group chat via skype.
Traceback (most recent call last):
File "C:\Program Files\Python\Python38-32\ga.py", line 12, in
skc.recent()
File "C:\Program Files\Python\Python38-32\lib\site-packages\skpy\chat.py", line 452, in recent
info = self.skype.conn("GET", "{0}/threads/{1}".format(self.skype.conn.msgsHost, json.get("id")),
File "C:\Program Files\Python\Python38-32\lib\site-packages\skpy\conn.py", line 219, in call
raise SkypeApiException("{0} response from {1} {2}".format(resp.status_code, method, url), resp)
skpy.core.SkypeApiException: ('404 response from GET https://azwus1-client-s.gateway.messenger.live.com/v1/threads/19:*********************', )
[Finished in 7.483s]
I'm just trying to test to send a simple chat to a groupchat but I'm not sure what is causing this error.
currently using this code
ch = sk.chats["19:***********************#thread.skype"] //due to privacy issue, i cant display the id
ch.sendMsg("testing")
whereas if I use the code this way for creating a new conversation,
ch = sk.contacts["live#123"].chat
ch.sendMsg("testing")
it will work.
Can someone enlighten me what is the issue with it? really appreciate a lot.

TypeError when calling expect method of pexpect module in Python 3

I am trying to use pexpect module (version 3.3) with Python 3.4.0. I get an error
TypeError: must be str, not bytes
when I call child.expect method.
Actual code is standard example from pexpect documentation:
child = pexpect.spawn('ssh foo#bar.com')
index = child.expect([pexpect.TIMEOUT, pexpect.EOF, ssh_newkey, '.*password:'])
Exactly the same code works properly with pexpect module (version 3.1), and Python version 2.7.6.
Pexpect documentation on GitHub states that pexpect version 3.3 requires Python 2.6 or 3.2 or above. Does anybody know if pexpect does not work with Python 3 for some reason despite what is stated in documentation for this module?
This is traceback output that I get:
Traceback (most recent call last):
File "/home/sambo9/python/python3-pexpect.py", line 17, in <module>
main()
File "/home/sambo9/python/python3-pexpect.py", line 13, in main
child.expect('.*password:')
File "/usr/local/lib/python3.4/dist-packages/pexpect/__init__.py", line 1451, in expect
timeout, searchwindowsize)
File "/usr/local/lib/python3.4/dist-packages/pexpect/__init__.py", line 1466, in expect_list
timeout, searchwindowsize)
File "/usr/local/lib/python3.4/dist-packages/pexpect/__init__.py", line 1535, in expect_loop
c = self.read_nonblocking(self.maxread, timeout)
File "/usr/local/lib/python3.4/dist-packages/pexpect/__init__.py", line 985, in read_nonblocking
self._log(s, 'read')
File "/usr/local/lib/python3.4/dist-packages/pexpect/__init__.py", line 908, in _log
second_log.write(s)
File "/usr/lib/python3.4/idlelib/PyShell.py", line 1339, in write
raise TypeError('must be str, not ' + type(s).__name__)
TypeError: must be str, not bytes
Additionally, I also see "OpenSSH" box pop open via GUI on Ubuntu prompting for password when I run the script. This does not happen under Python 2.7.6. In Python 2.7, I can login into system without any manual interaction - everything happens automatically via script.
From the documentation:
# In Python 3, spawnu should be used to give str to stdout:
child = pexpect.spawnu('some_command')
child.logfile = sys.stdout

Using numdisplay, "An existing connection was forced to close by the remote host"

I've been learning to use python in astronomy and for that I'm following this notes. In the very beginning the author does the following example:
>>> im = pyfits.getdata('http://das.sdss.org/www/cgi-bin/drC?RUN=3630&RERUN=40&CAMCOL=3&FIELD=83&FILTER=r')
>>> numdisplay.display(im,z1=1000,z2=1500)
I try to replicate it and I get:
>>> numdisplay.display(im,z1=1000,z2=1500)
Image displayed with Z1: 1000 Z2: 1500
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
numdisplay.display(im,z1=1000,z2=1500)
File "C:\Mine\Python\lib\site-packages\numdisplay\__init__.py", line 446, in display
_d.writeImage(bpix,_wcsinfo)
File "C:\Mine\Python\lib\site-packages\numdisplay\displaydev.py", line 513, in writeImage
self.writeData(_lx,_ydisp,_fpix[block,:])
File "C:\Mine\Python\lib\site-packages\numdisplay\displaydev.py", line 379, in writeData
self._writeHeader(opcode,self._MEMORY, -nbytes, x, y, frame, 0)
File "C:\Mine\Python\lib\site-packages\numdisplay\displaydev.py", line 542, in _writeHeader
self._write(a.tostring())
File "C:\Mine\Python\lib\site-packages\numdisplay\displaydev.py", line 580, in _write
nwritten = self._socket.send(s[-n:])
error: [Errno 10054] An existing connection was forced to close by the remote host
I don't understand what I'm doing wrong. I mean if I write numdisplay.open() everything is fine... I'm thinking that it might be my antivirus or something that doesn't let python to communicate with ds9... Can somebody help me?
Edit: Well it doesn't seem to be the antivirus. I stopped it and run the script and I got the same error.
I was getting similar error messages, and I just tried adding a non-'None' argument to the bufname argument and it works (my image is about 4096.4096):
numdisplay.display(data,bufname='imt4096')

Categories

Resources