How to correctly send messages daily in telegram bot? - python

I have a problem using the job_queue and run daily messages in my telegram bot. I have already read and tried every answer I have found in stack overflow and online, but somehow nothing works and I don't know what's wrong.
I want to send a message daily, but only after the /start command, and I want to shut down the bot and the scheduled messages with the /stop command. I am using version 13.5. Here's the code at the moment:
import logging, os, random, sys, random, datetime
from telegram import ParseMode, Update
from telegram.ext import Updater, CommandHandler, CallbackContext
...
def callback_daily(context: CallbackContext):
context.bot.send_message(
text="DAILY TEXT",
parse_mode=ParseMode.HTML
)
def start_handler(update: Update, context: CallbackContext):
context.bot.run_daily(callback_daily,
days=(0,1,2,3,4,5,6),
time=datetime.time(hour=20, minute=00, tzinfo=pytz.timezone("Europe/Rome")),
context=update.message.chat_id
)
update.message.reply_text(
"STARTED"
)
if __name__ == '__main__':
logger.info("### Starting Bot ###")
updater = Updater(TOKEN, use_context=True)
updater.dispatcher.add_error_handler(CommandHandler("error", error_handler))
updater.dispatcher.add_handler(CommandHandler("start", start_handler, pass_job_queue=True))
updater.dispatcher.add_handler(CommandHandler("help", help_handler))
...
run(updater)
logger.info("### Bot Started ###")
What I get at the moment is:
AttributeError: 'Bot' object has no attribute 'run_daily'
I have tried also many other things found here in Stackoveflow, so many that I don't even remember them, and somehow every answer shows a different method to run scheduled message (and not even one works at the moment).
What am I doing wrong here?

Related

DiscordPy Bot abnormally long shutdown times

So here's the crux of the problem. I'm using the Discord Py API (1.7.3). I have 2 bots I run that use it, Red Bot and the one I made myself. I've come to notice one little discrepancy that I can't troubleshoot successfully. If I kill Red Bot, like either by shutting down the host computer or otherwise, it leaves Chat immediately. If I do the same to my bot, it lingers for minutes at a time. It's driving me up the wall and I can't figure out why. I have another friend with his own completely independent bot, with the same issue.
There are 5 other modules, but the below is main and the most likely to have either the problem or the place for the solution.
from events import Events
from macros import Macros
from voting import Voting
from miscellaneous import Miscellaneous
from persistent import *
# Fetches configuration information
comList = []
discordAuthcode = ""
with open(DAC_FILE, "r") as discordAuthfile:
discordAuthcode = discordAuthfile.read().strip()
# Sets Google's credentials
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = GAJ_FILE
# Creates basic bot object
help_overwrite = commands.DefaultHelpCommand(no_category="Help")
intents_overwrite = discord.Intents.default()
intents_overwrite.members = True
intents_overwrite.messages = True
bot = commands.Bot(command_prefix=COM_PRFX, description="Gestalt's Help Menu", help_command=help_overwrite, intents=intents_overwrite)
# Creates a task to iterate randomly through creative messages
#tasks.loop(minutes=random.randint(1,5))
async def random_presence():
choice = presenceList[random.randint(0, len(presenceList)-1)]
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=choice))
# Creates a task to backup active nomination instances
#tasks.loop(minutes=5)
async def backup_nominations():
repickles(NBP_FILE, nominationMap)
# DEBUG: Executes on Interval, good for live-testing
##tasks.loop(seconds=3)
#async def backup_nominations():
# print(nominationMap)
# Bot Initialization
#bot.event
async def on_ready():
"""Initializes the bot's functions.
"""
# Feedback
print("{0.user} Version {1} has started.".format(bot, VERSION))
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="the beginning."))
# Starts Random Presence
random_presence.start()
# Starts backing up nominations list
backup_nominations.start()
# Adds Cogs to Bot
bot.add_cog(Events(bot))
bot.add_cog(Macros(bot))
bot.add_cog(Voting(bot))
bot.add_cog(Miscellenous(bot))
# Runs Bot
bot.run(discordAuthcode)
I've looked at Red Bot's handling of shutdown, and while it clearly puts a lot more effort into it, I didn't successfully transplant anything that worked. Could I please have some help?
Edit: I have also tried enabling logging, nothing is erroring out, the last entry is always it exiting the Event Loop.
Edit 2: I have replicated this problem on a barebones bot

Message from a telegram bot without a command(python)

I want to send a Message(call a function) every day at a given Time. Sadly this is not possible with message.reply_text('Test'). Is there any way i can do this? I could not find anything.
This is my current code:
import telegram.ext
from telegram.ext import CommandHandler, MessageHandler, Filters
import schedule
import time
API_KEY = 'XXXXXXXXXXX'
updater = telegram.ext.Updater(API_KEY)
dispatcher = updater.dispatcher
def start(update, context):
update.message.reply_text('Welcome!')
# problem:
def Test(update, context):
update.message.reply_text('Works!!!')
# running special functions every Day at a given Time
schedule.every().day.at("10:00").do(Test)
while True:
schedule.run_pending()
time.sleep(1)
def main():
# add handlers for start and help commands
dispatcher.add_handler(CommandHandler("start", start))
# start your bot
updater.start_polling()
# run the bot until Ctrl-C
updater.idle()
The schedule part works, I just don`t know how to send this Message.
Thanks for your help!
Update object, inside of the message field, has the from field which is a User Telegram object containing the user's ID.
Once you have the user's ID, you can use the sendMessage method in order to reply him easily.
To conclude, instead of:
update.message.reply_text('Welcome!')
You could do like so:
user_id = update.message.from.id
updater.sendmessage(chat_id=user_id, text="Welcome!")

Fetching messages in real time with Telethon from a Telegram channel

I am trying to fetch messages in real time from some Telegram channels. My code is as follow:
from telethon import TelegramClient, events, sync
import config
client = TelegramClient('anon', config.api_id, config.api_hash)
#client.on(events.NewMessage(chats='channel'))
async def my_event_handler(event):
print(event.raw_text)
The config document contains my credentials. Now this works, except that at some points there are delays of some seconds. And for some channels it completely misses some of the messages if I let the script run long enough. I also use Anaconda.
Is there some workaround to get real time messages without missing any of them?

How can I handle audio messages in pyTelegramBotAPI?

I'm using pyTelegramBotAPI as framework to create a telegram bot.
I'm having some troubles with handle audio messages and I can't understand where I am wrong.
Here my code:
# If user send an audio and it's a private chat
#bot.message_handler(content_types=["audio"])
def react_to_audio(message):
if message.chat.type == "private":
bot.reply_to(message, """What a nice sound! I'm not here to listen to some audio, tho. My work is to wish a good night to all members of a group chat""")
Can anyone help me?
i don't specifically know well how to use pyTelegramBotAPI because also i got problems i couldn't solve so i abandoned it for python-telegram-bot which is better documented in comparison to pyTelegramBotAPI, has a bigger community, is more actively developed and also have an active Telegram group where you can directly ask for help from other developers using this wrapper.
So if you are interested to change to python-telegram-bot, the code for your bot would look something like this:
from telegram import Update
from telegram.ext import Updater, MessageHandler, Filters
token = "" #Insert your token here
def message_handler(update, context):
update.message.reply_text("Hello")
def audio_handler(update, context):
if update.message.chat.type == "private": #Checks if the chat is private
update.message.reply_text("What a nice sound! I'm not here to listen to some audio, tho. My work is to wish a good night to all members of a group chat")
def main():
"""Start the bot."""
updater = Updater(token, use_context=True)
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
# on noncommand i.e message
# Use this if you want to handle also other messages
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, message_handler))
dispatcher.add_handler(MessageHandler(Filters.audio & ~Filters.command, audio_handler))
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
Here are also some official examples of bots made with this wrapper and the that you can use to better understand the wrapper, if you want more info regard this feel free to DM me on telegram #Husnainn.

Getting updates inside a function (Telegram bot, Python3, python-telegram-bot library)

I'm trying to make a telegram bot with https://github.com/python-telegram-bot/python-telegram-bot library in python3.
I want to make a message sender bot. This is my code now:
#!/usr/bin/env python
"""#==============================# Imports #==============================#"""
import logging, time, telegram
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from datetime import datetime
"""#==============================# Enable logging #==============================#"""
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.WARN)#DEBUG)
logger = logging.getLogger(__name__)
"""#==============================# Log error #==============================#"""
def error(update, context):
#Log Errors caused by Updates.
logger.warning("Update '%s' caused error '%s'", update, context.error)
"""#==============================# Bot commands #==============================#"""
def start(update, context):
update.message.reply_text("Bot joined the conversation!")
def get_additional_updates(update, message):
***My Problem***
"""#==============================# MAIN #==============================#"""
def main():
updater = Updater("<TOKEN>", use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start)
dp.add_handler(CommandHandler("send", get_additional_updates)
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
I don't know what should I do to get the updates inside the 'get_additional_updates' function.
What I want to do, is: I type /send, after this the bot waits for my message, I type my message in and send it. The problem is, that I can't figure it out how to get the second message (the message itself) to the 'get_additional_updates' function.
I can't find it in the documentation, and I'm very new to programming as well.
Please help me with the code I need to type there in order to get the additional messages.
Let me know if you can't understand what is my question, I'll try to explain better.
Thanks a lot!
P.S.:Sorry, if my english is bad, I'm trying to upgrade that as well.
You should use conversation bot ,Check the example here

Categories

Resources