Python telebot script (take picture every minute and send to telegram) - python

Hi I have been struggling with this script for a while and the last line is starting to drive me crazy. I want to take a picture every minute and send it to telegram.
import telebot
import picamera
# Set token
token = "PLACE TOKEN HERE"
# Connect to our bot
bot = telebot.TeleBot(token)
# Sets the id for the active chat
chat_id=PLACE CHAT ID HERE
# Get the photo
camera=picamera.PiCamera()
camera.capture('./capture.jpg')
camera.close()
# Sends a message to the chat
bot.send_photo(chat_id, photo=open('./capture.jpg', 'rb'))
ERROR: TypeError: send_photo() got an unexpected keyword argument 'photo'
Help would be greatly appreciated.

I have improved the script. If it helps anyone here is the code im currently using:
import time
import requests
import telebot
import picamera
from time import sleep
# Set token
token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# Connect to our bot
bot = telebot.TeleBot(token)
# Sets the id for the active chat
chat_id="xxxxxxxxx"
# Repeat function
def repeat():
# Set camera
camera=picamera.PiCamera()
# Take picture
camera.capture('./capture.jpg')
# Camera close
camera.close()
# Send photo to telegram
bot.send_photo(chat_id=chat_id, photo=open('capture.jpg', 'rb'))
# Sleep 60 seconds
time.sleep(60)
while True:
repeat()
It works but sometimes the script will crash with one of these errors:
requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))
requests.exceptions.ConnectionError: ('Connection aborted.', timeout())
Any idea how to solve those errors?

Related

How to publish to AWS MQTT after message was received

After importing the AWSIoTMQTTClient module with
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
I went ahead and configured the MQTT client connection
myMQTTClient = AWSIoTMQTTClient("my-clientid")
myMQTTClient.configureEndpoint("123abc-ats.iot.us-east-1.amazonaws.com", 8883)
myMQTTClient.configureCredentials(ROOT_KEY, PRIVATE_KEY, CERT)
myMQTTClient.connect()
I defined helloworld function that I want to use as a callback to catch the messages from the topic as:
def helloworld(client, params, packet):
print('...topic:', packet.topic)
print('...payload:', packet.payload)
myMQTTClient.publish(topic="home/fromserver", QoS=1, payload="{'message':'hello from server'}" )
Please note that the last line in the helloworld function I publish the message back to MQTT to the "home/from-server" topic.
I added two more lines to the script and run it
myMQTTClient.subscribe("home/to-server", 1, helloworld)
while True:
time.sleep(1)
I can fetch the messages from the to-server topic. But publishing the message to from-server topic crashes with AWSIoTExceptions.publishTimeoutException
How can I publish a message back to MQTT without raising the publishTimeoutException?

Telegram Bot - Connection Aborted

Hello has anyone had this error when using pyTelegramBotAPI:
raise ConnectionError(err, request=request) requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forced to be aborted by the remote host', None, 10054, None)).
This is the code I am using:
import telebot
import time
import logging
Token = TOKEN
bot = telebot.TeleBot(Token)
def send_signals(text):
#sendMessage
chats = chatID
try:
bot.send_message(chats, text)
except (ConnectionAbortedError, ConnectionResetError, ConnectionRefusedError, ConnectionError):
time.sleep(1)
bot.send_message(chats, text)
The bot has to send 3 messages, for example it sends a first message at 2:21 (it is not an absolute time), then another at 2:30 and when trying to send the last one sometimes I get this error. Or even from the first message it sends me the error.
Any idea how to solve it?

Socket Programming : how to receive data until a dot is received (Python)

Situation:
I am currently writing a client program with a provided server program
I need to send the command 'READ' and get a bunch of data from server
The server will just keep sending and lastly it will sd a dot
(".")
My task is to display all msg it send out (tgt with the dot)
I can successfully receive everything and displayed.
however i cannot exit the while loop(cannot successfully detect the dot)
Why is that?
Below is my code. thanks!
def READ(mySocket):
op="READ"
clientSocket.send(op.encode())
while(True):
try:
rcvmsg = clientSocket.recv(4096)
print("Server:{} ".format(rcvmsg.decode()))
if (rcvmsg.decode() == "."):
break
except :
print("some error happen" )
sys.exit(1)

BLE device does not make new /dev/input/eventX when it reconnects, using Python Gatt Library

I am new to python gatt module, and i am having a problem with reconnections.
Basically what I am trying to do is establish a connection with a Bluetooth Low Energy (BLE) device with the python gatt module( https://github.com/getsenic/gatt-python ) and then read the input from the /dev/input/eventX path with the evdev module. I also want to automate the reconnection process, so when the device gets out of range and comes back, it will reconnect and continue working normally.
The problem is that when the device disconnects, and eventually reconnects (via simple routine like this: catch disconnect message -> try to reconnect) if the reconnection has taken more than 2-3 minutes, the connection process does not make a new /dev/input/eventX path. This is not happening when the reconnection is successful in between the first 1-2 minutes.
The error I am getting when the 2-3 minutes have passed is:
File "/usr/lib/python3.7/site-packages/dbus/proxies.py", line 145, in
call
File "/usr/lib/python3.7/site-packages/dbus/connection.py", line 651, in call_blocking
dbus.exceptions.DBusException:
org.freedesktop.DBus.Error.NoReply: Did not receive a reply. Possible
causes include: the remote application did not send a reply, the
message bus security policy blocked the reply, the reply timeout
expired, or the network connection was broken.
The core of the script is the following:
def reconnect(mac_address):
try:
devices[mac_address].connect()
except:
print(f"thread from {mac_address} crashed")
class AnyDevice(gatt.Device):
shut_down_flag = False
def connect_succeeded(self):
super().connect_succeeded()
print(f"{self.mac_address} Connected")
def connect_failed(self, error):
super().connect_failed(error)
print(f"{self.mac_address} Connection failed.")
reconnect_thread = threading.Thread(target=reconnect, name=f'reconnect {self.mac_address}',args=(self.mac_address,))
reconnect_thread.start()
def disconnect_succeeded(self):
super().disconnect_succeeded()
print(f"{self.mac_address} Disconnected")
if not self.shut_down_flag:
reconnect_thread = threading.Thread(target=reconnect, name=f'reconnect {self.mac_address}',args=(self.mac_address,))
reconnect_thread.start()
def gatt_connect_device(mac_address):
global devices
devices.update({f'{mac_address}': AnyDevice(mac_address=f'{mac_address}', manager=manager)})
devices[f'{mac_address}'].connect()
#==== OPEN bd_addresses.txt JSON FILE ====#
if path.exists("bd_addresses.txt"):
with open("bd_addresses.txt", "r") as mac_addresses_json:
mac_addresses = json.load(mac_addresses_json)
else:
print("bd_addresses.txt file NOT FOUND\nPlace it in the same directory as the multiple_scanners.py")
#========================================#
devices={}
manager = gatt.DeviceManager(adapter_name='hci0')
for scanner_number in mac_addresses:
device_instance_thread=threading.Thread(target=gatt_connect_device, name=f'device instance for {mac_addresses[scanner_number]}', args=(mac_addresses[scanner_number],))
device_instance_thread.start()
time.sleep(3)
manager.run()

print udates in telegram via telethon

I am trying to print updates to my telegram acount . This is my code :
client = TelegramClient('session_name', api_id, api_hash, update_workers=4)
client.connect()
from telethon.tl.types import UpdateShortMessage, PeerUser
def callback(update):
print(1)
print('I received', update)
client.add_update_handler(callback)
whats wrong ? nothing prints .
First of all I suggest you add:
import logging
logging.basicConfig(level=logging.INFO)
So you can see what errors you are getting but can't yet see.
Significantly your program will end straight away because it never waits to receive any inbound messages. You will need to use something like client.loop.run_until_complete(somefunctionthattreadswater) at the end so that it hangs around until you press ctrl-C.

Categories