Why isn't my proximity alert Telegram bot functioning?

Hey everyone, I’m having trouble with a basic project I’m working on. I’m trying to set up a Telegram bot that sends me a notification when an object comes within 50cm of a sensor. I’ve got the Wi-Fi connection working, and I’m sure I’ve entered the correct bot token and ID. But for some reason, it’s just not sending any alerts. Here’s a simplified version of my code:

import telebot
from gpiozero import DistanceSensor
from time import sleep

BOT_TOKEN = 'your_bot_token_here'
CHAT_ID = 'your_chat_id_here'

bot = telebot.TeleBot(BOT_TOKEN)
sensor = DistanceSensor(echo=18, trigger=17)

def check_proximity():
    while True:
        distance = sensor.distance * 100
        if distance <= 50:
            bot.send_message(CHAT_ID, 'Object detected within 50cm!')
        sleep(1)

if __name__ == '__main__':
    check_proximity()

Can anyone spot what might be going wrong? I’m pretty new to this, so I might be missing something obvious. Any help would be much appreciated!

I encountered a similar issue when working on a proximity-based project. Have you verified that your bot is actually running and connected to Telegram’s servers? A simple way to test this is to add a startup message:

bot.send_message(CHAT_ID, ‘Bot is now running!’)

Place this right after your bot initialization. If you don’t receive this message, there might be an issue with your bot token or chat ID. Also, ensure your Wi-Fi connection is stable throughout the bot’s operation. Intermittent connectivity can cause message sending failures without throwing obvious errors.

hey sarahj, might be a power issue. check if ur sensor’s gettin enough juice. also, try printin the distance in ur loop to see if it’s actually detectin anything. sometimes these sensors can be finicky. good luck with ur project!

I’ve run into this problem before, and it can be frustrating. One thing that’s not immediately obvious is that the Telegram API has rate limits. If you’re sending too many messages too quickly, it might silently fail without throwing an error. Try adding a longer delay between checks, like 5 or 10 seconds instead of 1.

Also, make sure you’re running this script with sudo if you’re on a Raspberry Pi. The GPIO pins often require elevated permissions.

Lastly, double-check your CHAT_ID. It should be a number, not a string. If you’re using a group chat, you might need to prefix it with a minus sign.

If none of that works, you could try using a different library like python-telegram-bot instead of telebot. Sometimes switching libraries can solve mysterious issues like this.