简体   繁体   中英

Raspberry PI zero w PIR send to Telethon

i try to send the image from a usb webcam to a telegram group if motion is detected. the motion works, but i cant get it to send it to my group. so im working on to send a text instead. (with the picture i can figure out, but first i need to get the text working)

code:

import RPi.GPIO as GPIO
import time
from telethon import TelegramClient
 
SENSOR_PIN = 17
 
GPIO.setmode(GPIO.BCM)
GPIO.setup(SENSOR_PIN, GPIO.IN)


#Telegram settings
api_id='xxxxx'
api_hash='xxxxx'
phone='xxxx'

#Kamera Gruppe
chatid = -xxxxx

client = TelegramClient(phone, api_id, api_hash)


async def mein_callback(channel):
    print('motion detected!')
    await client.send_message(chatid, 'motion detected')
    
try:
    GPIO.add_event_detect(SENSOR_PIN , GPIO.RISING, callback=mein_callback)
    while True:
        time.sleep(100)
except KeyboardInterrupt:
    print ("Beende...")
GPIO.cleanup() 

error:

sys:1: RuntimeWarning: coroutine 'mein_callback' was never awaited RuntimeWarning: Enable tracemalloc to get the object allocation traceback

I don't know how the RPi library works, but I know Telethon is an async library, and from the looks of it, RPi is not.

You cannot use time.sleep() because that will block the entire asyncio event loop. You would need something like await asyncio.sleep() . It also seems you are never running client.start() , so the client won't be connected, so client.send_message would fail. I recommend you read through the asyncio documentation to understand this better. That said... the following should work, assuming RPi is not threaded:

import RPi.GPIO as GPIO
import asyncio
from telethon import TelegramClient
 
...

client = TelegramClient(phone, api_id, api_hash)

async def mein_callback(channel):
    print('motion detected!')
    await client.send_message(chatid, 'motion detected')

def schedule_mein_callback(channel):
    client.loop.create_task(mein_callback(channel))  # <- create a new task that will run in the future

async def main():
    async with client:  # <- start the client so `send_message` works
        GPIO.add_event_detect(SENSOR_PIN , GPIO.RISING, callback=schedule_mein_callback)  # <- not an async callback, GPIO can run it fine
        while True:
            await asyncio.sleep(100)  # <- no longer blocks, telethon can run fine

try:
    client.loop.run_until_complete(main())  # <- enter async-land
except KeyboardInterrupt:  # <- should generally be used before entering `async`
    print ("Beende...")
GPIO.cleanup() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM