I'm trying to code a telegram bot to remove any deleted accounts in the group chat but with telegram removing get_chat_members in later versions I'm at a lost, here's my current code how can I get all the members or loop through all members to check rather the account is deleted or not?
from telegram import *
from telegram.ext import *
from requests import *
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram.ext import CallbackQueryHandler, CallbackContext
from telegram.ext.dispatcher import run_async
from telegram.ext.jobqueue import Days
# Create a new Telegram bot & # Start the bot and connect to the Telegram API
updater = Updater(token="bot_token", use_context=True)
dispatcher = updater.dispatcher
# Define a command handler for the /start command, which prints a greeting
def start(update: Update, context: CallbackContext):
context.bot.send_message(chat_id=update.effective_chat.id, text="Hello! I am RDA_bot, a bot that removes deleted accounts from a Telegram group.")
# Define a command handler for the /remove command, which removes deleted accounts from the group
def remove(update: Update, context: CallbackContext):
# Get a list of all members of the group
members = #NEED HELP HERE
# Count how many members have deleted their account
deleted_accounts = 0
for member in members:
if member.user.is_deleted:
deleted_accounts += 1
# Send a message to the user with the number of deleted accounts
context.bot.send_message(chat_id=update.effective_chat.id, text=f"Removed {deleted_accounts} deleted accounts from the group.")
# Define a command handler for the /remove command, which removes deleted accounts from the group
def remove(update: Update, context: CallbackContext):
# Get a list of all members of the group
members = #NEED HELP HERE
# Loop through each member of the group
for member in members:
# If the member's account has been deleted, kick them from the group
if member.user.is_deleted: #NEED TO CHECK IF THE USER IS DELETED
context.bot.kick_chat_member(chat_id=update.effective_chat.id, user_id=member.user.id, until_date=0)
# Create a job that runs every 24 hours to remove deleted accounts from the group
job_queue = updater.job_queue
job = job_queue.run_repeating(remove, interval=Days(1), first=0)
# Add the command handlers to the dispatcher
start_handler = CommandHandler("start", start)
dispatcher.add_handler(start_handler)
remove_handler = CommandHandler("remove", remove)
dispatcher.add_handler(remove_handler)
# Start the bot
updater.start_polling()
tried get_chat_members(chat_id) but that's no longer available.
The Bot API does not contain functionality to retrieve the full member list of a chat. I'm also not aware of any reliable way of checking if an account has been deleted. Maybe getChat returns a helpful error message in that case, but I haven't tried that so far.
Related
I want to make a Telegram bot with Python and I want it to constantly read messages from a different private chat . I want to find a way to make the bot receive all the messages which I receive in the given chat. My struggle is redirecting the messages from one private chat to the chat with the bot. Is it possible to do it? If yes, how can it be done?
I have tried googling the subject, but I haven't found any satisfying answer.
Thank you.
Check this package :
https://python-telegram-bot.org/
You would juste have to add a message handler to your bot instance.
You have to talk to telegram BotFather to get a token. Then you have to create a instance of a bot in your code and subscribe to new messages
from telegram.ext import Update, MessageHandler, Filters
# Define a function to handle the messages that the bot receives
def message_handler(update, context):
# Get the message from the update
message = update.message
# Print the message to the console
print(message.text)
# Create the Updater and pass it the bot's token
updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# Add a message handler that will be called for any message
dp.add_handler(MessageHandler(Filters.text, message_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()
Good evening.
I hope that you are well.
I have posted an excerpt below of some Telegram bot code which auto forwards any messages it receives to another channel which has the bot added :-
api_key = ""
bot = telebot.TeleBot(api_key)
chat_id = "1234"
#bot.message_handler(func=lambda m: True)
def handle_posts(m: telebot.types.Message):
message_from = m.from_user.id
if message_from == 123456 or message_from == 654321:
print("You are an authorized user")
bot.forward_message(chat_id, m.chat.id, m.message_id)
else:
print("You are not an authorized user")
This code works fine for any text based messages that are sent to the bot (which includes standard formatting such as Bold, Italic, Underline, Emojis, Hyperlinks etc.) however if I attempt to attach an image to a message and then send it, the message is not forwarded on at all.
Does anyone have any idea how I can handle image based messages so that they forward successfully please?
Does it need another function that deals with a different telebot.types method perhaps?
Many thanks in advance
Jimmy
I have a bot that does something like this, but I only need to handle text and photos separately. I hope this code snipped helps!
# imports
from logging import Filter
from telegram import Update
from telegram.ext import *
import telegram
from dotenv import load_dotenv
import os
# get the telegram bot api_key from environment file
load_dotenv()
API_KEY = os.getenv('API_KEY')
# you will need the groub_b_id saved as a global variable or
# in some other document
group_b_id = 1234567890
# create the bot, updater, and dispatcher
bot = telegram.Bot(token=API_KEY)
updater = Updater(API_KEY, use_context=True)
dp = updater.dispatcher
def get_chat_id(update: Update, context: CallbackContext):
# gets the chat_id of the current chat
global bot
chat_id = update.effective_chat.id
bot.send_message(chat_id, "This chat's id is: " + str(chat_id))
def auto_forward(update: Update, context: CallbackContext):
# automatically forwards messages from this chat to
# chat_b
global bot, group_b_id
chat_id = update.effective_chat.id
username = update.effective_message.from_user.name
chat_title = update.effective_message.chat.title
msg_txt = update.effective_message.text
bot.send_message(
group_b_id,
text=f"'{msg_txt}'\nwas just sent in chat {chat_title} by {username}"
)
def auto_forward_image(update: Update, context: CallbackContext):
# get variables
global bot, group_b_id
chat_id = update.effective_chat.id
username = update.effective_message.from_user.name
chat_title = update.effective_message.chat.title
# get the third best quality photo
photos = len(update.message.photo)
img_index = max(photos-3, 0) # change -3 to -2 to get second best etc
img = update.message.photo[img_index]
# send message to GroupB the group that you want the stuff forwarded to
bot.send_message(group_b_id, str(username) + " just sent me an image from the `" + str(chat_title) + "` chat:")
bot.send_photo(group_b_id, img)
# sets up the handlers
dp.add_handler(CommandHandler('get_chat_id', get_chat_id))
dp.add_handler(MessageHandler(Filters.text, auto_forward))
dp.add_handler(MessageHandler(Filters.photo, auto_forward_image))
# Start the Bot
updater.start_polling()
updater.idle()
just make sure that you add the bot to both chats as an admin or this will not work since the bot needs admin priveleges to respond to all messages not just commands.
I have a Telegram Bot on aiogram, and I want to be notified when my bot is added or removed from channels.
But my code only works on groups.
What needs to be done to work on channels as well?
And here is the code:
import logging
from aiogram import Bot, Dispatcher, executor, types
from config import API_TOKEN
logging.basicConfig(level=logging.INFO)
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)
#dp.message_handler(content_types=[types.ContentType.NEW_CHAT_MEMBERS, types.ContentType.LEFT_CHAT_MEMBER])
async def check_channel(message: types.Message):
print(message)
if __name__ == "__main__":
executor.start_polling(dp, skip_updates=True)
Use my_chat_member_handler instead.
More info: https://core.telegram.org/bots/api-changelog#march-9-2021
Added two new update types
Added updates about member status changes in chats, represented by the
class ChatMemberUpdated and the fields my_chat_member and chat_member
in the Update class. The bot must be an administrator in the chat to
receive chat_member updates about other chat members. By default, only
my_chat_member updates about the bot itself are received.
I made my first simple telegram bot with python-telegram-bot. Here's the code:
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
token = '1234567890'
updater = Updater(token=token, use_context=True)
dispatcher = updater.dispatcher
def start(update, context):
context.bot.send_message(chat_id = update.effective_chat.id, text=f"hey,{update.effective_chat.username}!")
def unknown(update, context):
context.bot.send_message(chat_id=update.effective_chat.id, text="Sorry, didn't understand")
unknown_handler = MessageHandler(Filters.command, unknown)
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)
dispatcher.add_handler(unknown_handler)
updater.start_polling()
I kept changing the message text in the code and then executing it, checking what happens in the bot. What I ended up is every time I do start, the bot sends any of the old message versions together with new one. I revoked the token and it helped.
My question is what happens under the hood and why the latest version of the code doesn't replace the old ones? Also, how can I deal with it without having to revoke token every time?
i am developing a python script for my telegram right now. The problem is:
How do I know when my bot is added to a group? Is there an Event or something else for that?
I want the Bot to send a message to the group he´s beeing added to which says hi and the functions he can.
I dont know if any kind of handler is able deal with this.
Very roughly, you would need to do something like this: register an handler that filters only service messages about new chat members. Then check if the bot is one of the new chat members.
from telegram.ext import Updater, MessageHandler, Filters
def new_member(bot, update):
for member in update.message.new_chat_members:
if member.username == 'YourBot':
update.message.reply_text('Welcome')
updater = Updater('TOKEN')
updater.dispatcher.add_handler(MessageHandler(Filters.status_update.new_chat_members, new_member))
updater.start_polling()
updater.idle()
With callbacks (preferred)
As of version 12, the preferred way to handle updates is via callbacks. To use them prior to version 13 state use_context=True in your Updater. Version 13 will have this as default.
from telegram.ext import Updater, MessageHandler, Filters
def new_member(update, context):
for member in update.message.new_chat_members:
if member.username == 'YourBot':
update.message.reply_text('Welcome')
updater = Updater('TOKEN', use_context=True) # use_context will be True by default in version 13+
updater.dispatcher.add_handler(MessageHandler(Filters.status_update.new_chat_members, new_member))
updater.start_polling()
updater.idle()
Please note that the order changed here. Instead of having the update as second, it is now the first argument. Executing the code below will result in an Exception like this:
AttributeError: 'CallbackContext' object has no attribute 'message'
Without callbacks (deprecated in version 12)
Blatantly copying from mcont's answer:
from telegram.ext import Updater, MessageHandler, Filters
def new_member(bot, update):
for member in update.message.new_chat_members:
if member.username == 'YourBot':
update.message.reply_text('Welcome')
updater = Updater('TOKEN')
updater.dispatcher.add_handler(MessageHandler(Filters.status_update.new_chat_members, new_member))
updater.start_polling()
updater.idle()