I’m new to making Telegram bots and I’ve got a basic setup going. Here’s what I’ve done so far:
function handleMessage($message) {
$reply = '';
switch ($message) {
case 'Hello':
$reply = 'Hey there!';
break;
case 'Who are you?':
$reply = 'I'm BotMcBotface';
break;
case 'How's it going?':
$reply = 'Pretty good, thanks for asking!';
break;
}
return $reply;
}
$botToken = 'your_token_here';
$chatId = 'user_chat_id';
$response = handleMessage($userMessage);
$apiUrl = "https://api.telegram.org/bot{$botToken}/sendMessage?chat_id={$chatId}&text={$response}";
file_get_contents($apiUrl);
I think this should work, but I haven’t tested it yet. I’ve got two questions:
How can I make the bot send an image from a URL?
Is there a way to keep track of how many users have interacted with the bot? Maybe store their IDs in a database and have a /stats command to show the count?
yo, ur code looks decent for a start. for sending pics, try the sendPhoto method. it’s pretty straightforward.
as for tracking users, yeah a database is the way to go. you could use something simple like SQLite. just add new users as they interact and bam, you’ve got ur stats.
I’ve been working with Telegram bots for a while now, and I can share some insights. For sending images, you’re better off using the Telegram Bot API library instead of raw HTTP requests. It simplifies the process and handles errors more gracefully.
As for tracking user stats, I’d recommend using Redis instead of a traditional database. It’s blazing fast for simple key-value storage, which is perfect for keeping user IDs. You can easily increment a counter each time a new user interacts with the bot.
One thing to keep in mind: make sure you’re complying with data protection regulations when storing user information. It’s a common oversight that can lead to headaches down the line.
Lastly, consider implementing rate limiting to prevent abuse. You’d be surprised how quickly some users can hammer your bot with requests if left unchecked.
Your code looks like a good start for handling basic text messages. For sending images, you can use the sendPhoto method instead of sendMessage. Here’s a quick example:
As for tracking user stats, you’re on the right track with storing user IDs in a database. You could use MySQL or SQLite to keep this data. Each time a user interacts with the bot, check if their ID exists in the database. If not, add it. For the /stats command, just query the database for the total count of unique users.
Remember to handle potential errors and implement proper security measures, especially when dealing with user data.