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.
Related
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
My goal is to create a Telegram listener on a specific channel that copies new messages and posts them as tweets on Twitter. So far the python I wrote works well when I run it on my computer, when I send a mock message on my Telegram channel, it detects that a message has been sent, goes down the code, and a tweet is created with the text.
However, this is not the case when I try to run in on an AWS instance (ubuntu).
when running the following code:
import tweepy
from telethon import TelegramClient, events
auth = tweepy.OAuthHandler("", "")
auth.set_access_token("", "")
api = tweepy.API(auth)
print("start")
# Listen to new messages on Telegram Channel
bot = TelegramClient("bot", api_id, api_hash).start(bot_token=bot_token)
with bot:
print("bot-start")
#client.on(events.NewMessage(chats=ChannelURL))
async def newmessagelistener(event):
print("action detected")
client.start()
client.run_until_disconnected()
Things start out ok at the beginning, but then when I write a new test message on the telegram channel - nothing, no "action detected" is returned, only "start" and "bot-start", no tweet is posted.
Any ideas as to what's going on?
Thanks in advance!
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?
I have recently created a simple bot for telegram using the pyTelegramBotAPI (telebot).
I added a message handler that is supposed to handle every message, including the ones that appear on a group when a new user joins, which are still Message objects a non-null new_chat_members property.
import telebot
bot = telebot.TeleBot(TOKEN)
[...]
#bot.message_handler(func=lambda m: True)
def foo(message):
bot.send_message(message.chat.id,"I got the message")
bot.polling()
Even so, the bot does not reply with the "I got the message" string when I add a new user, although it does catch other messages.
Why is this happening? Is this a problem about the message handler? Is there maybe a more general handler that is sure to catch every update?
Thank you
you should specify "new_chat_members" as content-types.
Here is a sample working snippet that welcomes new users:
import telebot
bot = telebot.TeleBot(TOKEN)
#bot.message_handler(content_types=[
"new_chat_members"
])
def foo(message):
bot.reply_to(message, "welcome")
bot.polling()
I was wondering if I can automatically download files from other telegram bots. I've searched online how to make a Python bot (or a Telegram bot written in Python) which do this, but I didn't find anything. Can someone help me?
Interaction between bots in telegram directly isn't possible since the Bot API doesn't support that.
But you can use MTProto libraries to automate almost all interactions with bots (including file downloading). since these libs simply automate regular user accounts, they don't have the limitations of the bot api.
Here is an example to download a file using telethon lib :
from telethon import TelegramClient, events
api_id = <API_ID>
api_hash = '<API_HASH>'
client = TelegramClient('session', api_id, api_hash)
BOT_USER_NAME="#filesending_sample_bot" # the username of the bot that sends files (images, docs, ...)
#client.on(events.NewMessage(func=lambda e: e.is_private))
async def message_handler(event):
if event.message.media is not None: # if there's something to download (media)
await client.download_media(message=event.message, )
async def main():
await client.send_message(BOT_USER_NAME, 'some text or command to trigger file sending') # trigger the bot here by sending something so that the bot sends the media
client.start()
client.loop.run_until_complete(main())
client.run_until_disconnected()
and in my example I created a minimal telegram bot in javascript that sends a photo (as Document) as it receives any message to test the above script out (but you configure the above script to match with your case):
const bot = new (require("telegraf"))(<MY_BOT_TOKEN>);
bot.on("message", (ctx) => ctx.replyWithDocument("https://picsum.photos/200/300"));
bot.launch();
Note that you must connect using a regular telegram account (not using a bot token but rather a phone number) for this to work. If using a telegram bot is a must, you can use the script in the background (by running it as a new process or as a REST api, etc...) and return a result to the telegram bot.