Redirect messages automatically in Telegram - python

I want to make automation that gets a message from a group, that we'll call group A.
And send it into group B.
I should use Telegram API or Telegram BOTs to solve this?
And how i can solve this problem using python?

I was having this same problem and figured this out:
# imports
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}"
)
# sets up the handlers
dp.add_handler(CommandHandler('get_chat_id', get_chat_id))
dp.add_handler(MessageHandler(Filters.text, auto_forward))
# Start the Bot
updater.start_polling()
updater.idle()
just make sure that you add the bot as an admin to both chats and this will work!

Related

Getting TypeError: delete_message() missing 1 required positional argument: 'self', when trying to delete a Bot message in Telegram Bot

I am using 'python-telegram-bot' when trying to delete the previous message send by the Bot above got raised!
my code:
updater = Updater(BOT_TOKEN, use_context=True)
dispatcher = updater.dispatcher
def start (update: Update, context: CallbackContext):
msg_info = update.message.reply_text('Hi')
print(msg_info)
msg_id = msg_info['message_id']
chat_id = msg_info['chat']['id']
from telegram import Bot
status = Bot.delete_message(chat_id=chat_id, message_id=msg_id)
print(status)
def handle_inputs (update: Update, context: CallbackContext):
comd = update.message.text
if (comd == '/start'):
start(update, context)
else:
update.message.reply_text("Sorry '%s' is not a valid command" % update.message.text)
def main():
updater.dispatcher.add_handler(MessageHandler(Filters.text, handle_inputs))
updater.start_polling()
if __name__ == '__main__':
main()
I am new to Telegram bot. What I've tried is checking the some documentation, but still couldn't pass through the problem.
I just want to delete the message which is currently send by the bot
Please look at the following example.
You using the class instead the instance. Bot is a class object. You need bot = Bot('token'). bot is now an instance of type Bot. and now bot.delete_message() will work as now self is defined.

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!")

Telegram bot ConversationHandler ignores fallbacks

I have an issue with the Telegram bot (python-telegram-bot). I've made ConversationHandler, but the "fallbacks" won't work. Bot just ignores the "/stop " command. When I send "/stop" the bot sends me "First handler" instead of "GoodBye". What's wrong?
import os
import telegram
from telegram.ext import (ConversationHandler,
CommandHandler,
MessageHandler,
Filters,
Updater
)
from dotenv import load_dotenv
load_dotenv()
TELEGRAM_TOKEN = os.environ['TELEGRAM_TOKEN']
USER_ID = os.environ['USER_ID']
bot = telegram.Bot(token=TELEGRAM_TOKEN)
updater = Updater(token=TELEGRAM_TOKEN)
def start(update, context):
context.bot.send_message(chat_id=update.effective_chat.id,
text='hi')
return 1
def stop(update, context):
context.bot.send_message('Good Bye')
return ConversationHandler.END
def first_handler(update, context):
context.bot.send_message(chat_id=update.effective_chat.id,
text='First handler')
return 1
conv_handler = ConversationHandler(
entry_points=[CommandHandler('Start', start)],
states={
1: [MessageHandler(Filters.text, first_handler,
pass_user_data=True)],
},
fallbacks=[CommandHandler('stop', stop)]
)
dispatcher = updater.dispatcher
dispatcher.add_handler(conv_handler)
updater.start_polling()
updater.idle()
According to the documentation, the MessageHandler(Filters.text, ...) is handling all text messages, including the /stop command. However, fallbacks are only being triggered if none of the above handlers were able to deal with the message.
You may exclude commands from the MessageHandler:
MessageHandler(
Filters.text & (~ Filters.command),
first_handler,
)
The syntax for combining filters is documented here.

How to get the Chat or Group name of Incoming Telegram message using Telethon?

I have this code
from telethon.sync import TelegramClient, events
with TelegramClient('name', api_id, api_hash) as client:
#client.on(events.NewMessage(pattern=pattern))
async def handler(event):
await event.reply("Here should be the Chat or Group name")
How to implement this?
if we are talking only about groups/channels
chat_from = event.chat if event.chat else (await event.get_chat()) # telegram MAY not send the chat enity
chat_title = chat_from.title
Else (If we want to get the full name of chat entities, including Users):
from telethon import utils
chat_from = event.chat if event.chat else (await event.get_chat()) # telegram MAY not send the chat enity
chat_title = utils.get_display_name(chat_from)
get_display_name() actually gets a name that you would see. Works for types User, Channel, Chat
That method shall not have await

Telegram echo bot for channels

I have the following telegram bot written in Python (3.x):
import telebot
import subprocess
from telebot import types
import os
bot = telebot.TeleBot(os.environ['BOT_API_TOKEN'])
#bot.message_handler(commands=['start'])
def save(messages):
for m in messages:
if "keyword" in m.text:
f = open("channel", "a")
f.write(m.text + "\n")
f.close()
bot.send_message(m.chat.id, "Saved!")
bot.set_update_listener(save)
bot.polling()
The idea is to store in the file channel the messages that contain the word keyword. This bot works perfectly if I talk to him, but if I add the bot to a channel, it doesn't work. The bot has disable the privacy mode and enable the joingroups option.
I have another bot that do the same but with different code:
import logging
import os
from telegram.ext import Updater, MessageHandler, Filters
updater = Updater(token=os.environ['BOT_API_TOKEN'])
dispatcher = updater.dispatcher
def save(bot, update):
print(update.message.text)
if "keyword" in update.message.text:
f = open("channel", "a")
f.write(update.message.text + "\n")
f.close()
bot.sendMessage(chat_id=update.message.chat_id, text="Saved!")
save_handler = MessageHandler(Filters.text, save)
dispatcher.add_handler(save_handler)
updater.start_polling()
I don't mind in which version can you help me.
If you want to handle channel messages, you need to parse channel_post field instead of message field.
You can lockup Update section of official document for more details.

Categories

Resources