how to schedule a telegram bot to send a message? - python

I am trying to create a Telegram bot that sends a message at a specific time, 5:30pm. However, the ways a was trying are not correct.
I wanted to trigger send_message regarding to the time and without the necessity of the user to send any /command.
import telebot
import datetime
TOKEN = 'MyToken'
bot = telebot.TeleBot(TOKEN)
#bot.message_handler(commands=['start'])
def send_welcome(message):
message_id=message.chat.id
bot.reply_to(message,"Welcome")
bot.polling()
Until now I was trying to add something like that, of course it is not python but kind of pseudocode just to explain:
if currenttime=17:30
send_message(idchat, "mymessage")
Thank you in advance.

If I understand correctly, you need to check your system time before sending a message, you could use the following code [source]:
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
To send a message you could use the following code [source]:
def test_send_message():
text = 'CI Test Message'
tb = telebot.TeleBot(TOKEN)
ret_msg = tb.send_message(CHAT_ID, text)
assert ret_msg.message_id
To compare the time, you may use:
if current_time=='17:30:00':
test_send_message()

You can use schedule python library.
First of all import the necessary modules
import schedule
import time
import telegram
Then you have to create a function that will repeat in every x time.
Here the bot will send me message in every 5 seconds.
TOKEN='your_token'
bot = telegram.Bot(token=TOKEN)
def job():
bot.sendMessage(chat_id=<chat_id>, text="Hello")
schedule.every(5).seconds.do(job)
while True:
schedule.run_pending()
time.sleep(1)
For more informations about schedule Read the documentation

Related

telegram bot in python for sending files doesnt work, but I dont know why [duplicate]

Hi i want to send message from bot in specific time (without message from me), for example every Saturday morning at 8:00am.
Here is my code:
import telebot
import config
from datetime import time, date, datetime
bot = telebot.TeleBot(config.bot_token)
chat_id=config.my_id
#bot.message_handler(commands=['start', 'help'])
def print_hi(message):
bot.send_message(message.chat.id, 'Hi!')
#bot.message_handler(func=lambda message: False) #cause there is no message
def saturday_message():
now = datetime.now()
if (now.date().weekday() == 5) and (now.time() == time(8,0)):
bot.send_message(chat_id, 'Wake up!')
bot.polling(none_stop=True)
But ofc that's not working.
Tried with
urlopen("https://api.telegram.org/bot" +bot_id+ "/sendMessage?chat_id=" +chat_id+ "&text="+msg)
but again no result. Have no idea what to do, help please with advice.
I had this same issue and I was able to solve it using the schedule library. I always find examples are the easiest way:
import schedule
import telebot
from threading import Thread
from time import sleep
TOKEN = "Some Token"
bot = telebot.TeleBot(TOKEN)
some_id = 12345 # This is our chat id.
def schedule_checker():
while True:
schedule.run_pending()
sleep(1)
def function_to_run():
return bot.send_message(some_id, "This is a message to send.")
if __name__ == "__main__":
# Create the job in schedule.
schedule.every().saturday.at("07:00").do(function_to_run)
# Spin up a thread to run the schedule check so it doesn't block your bot.
# This will take the function schedule_checker which will check every second
# to see if the scheduled job needs to be ran.
Thread(target=schedule_checker).start()
# And then of course, start your server.
server.run(host="0.0.0.0", port=int(os.environ.get('PORT', 5000)))
I hope you find this useful, solved the problem for me :).
You could manage the task with cron/at or similar.
Make a script, maybe called alarm_telegram.py.
#!/usr/bin/env python
import telebot
import config
bot = telebot.TeleBot(config.bot_token)
chat_id=config.my_id
bot.send_message(chat_id, 'Wake up!')
Then program in cron like this.
00 8 * * 6 /path/to/your/script/alarm_telegram.py
Happy Coding!!!
If you want your bot to both schedule a message and also get commands from typing something inside, you need to put Thread in a specific position (took me a while to understand how I can make both polling and threading to work at the same time).
By the way, I am using another library here, but it would also work nicely with schedule library.
import telebot
from apscheduler.schedulers.blocking import BlockingScheduler
from threading import Thread
def run_scheduled_task():
print("I am running")
bot.send_message(some_id, "This is a message to send.")
scheduler = BlockingScheduler(timezone="Europe/Berlin") # You need to add a timezone, otherwise it will give you a warning
scheduler.add_job(run_scheduled_task, "cron", hour=22) # Runs every day at 22:00
def schedule_checker():
while True:
scheduler.start()
#bot.message_handler(commands=['start', 'help'])
def print_hi(message):
bot.send_message(message.chat.id, 'Hi!')
Thread(target=schedule_checker).start() # Notice that you refer to schedule_checker function which starts the job
bot.polling() # Also notice that you need to include polling to allow your bot to get commands from you. But it should happen AFTER threading!

Get updates only one time per message

Im building a Telegram bot using the official API and python with the requests lib
I`ve add a command named text, that return "example text" when it is called. Until here all ok, but the bot only send a response when the python script is executed
So I do that the script execute indefinitely with a white True condition.
The problem is that if I execute indefinitely the script it will be making requests all the time to the API, so if I check the last message all the time with the script, the last message will be /text until I write another message.
How can do that the function that read the command will execute only one time when a new command will requested?
The code is the next:
# TELEGRAM BOT USING THE API
import requests as req
from dotenv import load_dotenv
from pprint import pprint
import re
import os
config = load_dotenv(".env")
teletoken = os.environ.get("telegram_token")
uri = f"https://api.telegram.org/bot{teletoken}/"
# Dynamic Telegram API method
def method(method):
return f"{uri}{method}"
# Response to a command
def get_and_response(chat_id: str or int):
updates = req.get(method("getUpdates"))
response = updates.json()
command_regex = re.findall("^/text*", response["result"][-1]["message"]["text"])
if command_regex == ["/text"]:
req.post(method("sendMessage"), data={"chat_id": chat_id, "text": "Example text"})
if __name__ == "__main__":
while True:
get_and_response(*chat_id*)

How to get the message id telegram channel from my bot and remove that message?

hi and thanks for your answer. i want to create a bot for forward message to my channel and delete the last message every 1 minute
i made that but i have some problem for removing the last message. i cant get the last message id from my channel to the bot.
my source is:
from telegram.bot import Bot
from telegram.update import Update
from telegram.ext.updater import Updater
from telegram.ext.callbackcontext import CallbackContext
from telegram.ext.messagehandler import MessageHandler
from telegram.ext.filters import Filters
from telegram.chataction import ChatAction
from time import sleep
import telegram_send
import socket
import telegram
import json
api_key="My API Key"
user_id = "My User Id"
updater = Updater(api_key, use_context=True)
bot = telegram.Bot(token=api_key)
def echo(update: Update, context: CallbackContext):
context.bot.send_chat_action(chat_id=update.effective_chat.id, action=ChatAction.TYPING)
sleep(60)
if update.message['photo'] == []:
bot.send_message(chat_id=user_id, text=update.message.text)
else:
fileID = update.message['photo'][-1]['file_id']
context.bot.sendPhoto(chat_id = user_id,caption=update.message['caption'],photo = fileID)
msg_id = update.message._id_attrs[]
#------------- And Also i user that too -------------
#msg_id=update.message.message_id
#------------- -------------
context.bot.delete_message(chat_id=user_id, message_id=msg_id)
update.effective_chat
update.effective_user
update.effective_message
print(json.dumps(update.to_dict(), indent=2))
dp = updater.dispatcher
dp.add_handler(MessageHandler(Filters.document | Filters.photo, echo))
dp.add_handler(MessageHandler(Filters.text, echo))
updater.start_polling()
and when i use that code this error will show:
The message_id that you want to remove is not exist....
actually i type a message id in manually for delete message and it was work
but i want to delete that message auto
please help me to do that. thanks
I fixed That With Python-Telegram-Bot Version 20
Read This Docs:
https://docs.python-telegram-bot.org/en/v20.0a2/

Telethon python keeps re-downloading photos

I've been scratching my head for the past half hour, but I can't fix this error, let me explain.
Basically what I'm trying to do is to make a simple script that will download both texts and photos from the last 6 days, the script works fine in everything except that when I re-run it, it will download again photos ending up with duplicated images.
This is the code:
from datetime import timedelta
from datetime import datetime
from telethon import TelegramClient
date = datetime.now() + timedelta(-6)
api_id = 123
api_hash = 'XXX'
client = TelegramClient('SESSION', api_id, api_hash)
#Blank files have been already created
async def main():
with open("downloadedids.txt", "r+") as archivio, open("messagesaved.txt", "r+") as scaricare:
async for message in client.iter_messages('test', offset_date=date, reverse=True): ##I want to download only messages 6 days ago to now
if str(message.id) not in str(archivio.read()):
if (message.photo):
await message.download_media("Include")
scaricare.write(str(message.text))
archivio.write(str(message.id) + "\n")
with client:
client.loop.run_until_complete(main())
Maybe the problem is related to async?
It's downloading it again because you are telling it to! Perhaps you want to do a checksum on the existing file and if it matches, don't keep the second one?

slack python api delete message

I am trying to use my bot to delete certain messages in a slack channel with this api call
import os
import time
import re
from slackclient import SlackClient
slack_client = SlackClient(
'xsssssseeeeeeee')
slack_mute_bot_id = None
def delete_message(slack_event):
for event in slack_event:
if event["type"] == "message":
message_text = event['text']
time_stamp = event['ts']
channel_id = event['channel']
slack_client.api_call(
'chat.delete',
channel=channel_id,
ts=time_stamp,
as_user=True
)
print(message_text + " delted")
if __name__ == "__main__":
if slack_client.rtm_connect(with_team_state=False):
slack_mute_bot_id = slack_client.api_call("auth.test")["user_id"]
while True:
# print(slack_client.rtm_read())
delete_message(slack_client.rtm_read())
time.sleep(1)
else:
print("Connection failed. Exception traceback printed above.")
I do not get any error message after doing this and the bot does not delete the message. I am using the bot user token. I have benn able to send message succesfully but the delete method does not work and still gives np responses
Refer - https://api.slack.com/methods/chat.delete
When used with a user token, this method may only delete messages
that user themselves can delete in Slack.
When used with a bot token, this method may delete only messages
posted by that bot.
I got stumbled into the same thing.

Categories

Resources