Telegram echo bot for channels - python

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.

Related

Redirect messages automatically in Telegram

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!

discord-ui Button Listener called twice

I've an issue I can't fix.
Indeed, I'm trying to develop a discord bot, and when asking some questions by DM, the bot is publishing a message to a specific channel with a button, until there everything works fine.
But I'd try to catch the event on button click, I'm using discord-ui v5 with discord.py v1.7 and Python 3.8.
I register my listener which is well called, this listener aims to DM the user who clicked on.
Unfortunately, the listener is called twice, the direct issue is user has twice the same message, that I wouldn't have.
Here my code :
main.py :
import discord
import locale
import os
from discord.ext import commands
from discord_ui import UI, Button, Components, Listener
from dotenv import load_dotenv
from pathlib import Path
from src.workflows.main import MainWorkflow
from src.workflows.subscription import SubscriptionWorkflow
from src.listeners.awesome_listener import MyAwesomeListener
path = Path()
load_dotenv(path.resolve() / ".env")
intents = discord.Intents.default()
intents.members = True
locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')
bot = commands.Bot(command_prefix = "!", intents=intents)
ui = UI(bot)
components = Components(bot)
workflow = MainWorkflow()
#bot.command()
async def my_command(ctx):
...
signup_channel = bot.get_channel(signup_channel_id)
""" EVERYTHING WORKS FINE UNTIL THERE """
sent_message = await signup_channel.send(message_for_run, components=[
Button(label="JLabel", color="green", custom_id="my_id"),
], listener=MyAwesomeListener(workflow))
bot.run(os.getenv("DISCORD_BOT_TOKEN"))
awesome_listener.py :
from discord_ui import Listener
from src.workflows.subscription import SubscriptionWorkflow
class NewRunListener(Listener):
def __init__(self, workflow) -> None:
self.subscription_workflow = SubscriptionWorkflow()
self.workflow = workflow
#Listener.button("my_id")
async def my_func(self, ctx):
""" THE CODE BELOW IS EXECUTED TWICE """
cheers = await self.subscription_workflow.cheers(ctx, self.workflow.run)
await ctx.author.send(cheers)
I'm pretty sure it's an idiot mistake but I can't figure it out.
Any help would be appreciated !
Thanks !
From what I understand you want to know who clicked a button. In that case you can use: interaction = await self.bot.wait_for("button_click") and then it’s simple to grab the user using interaction.user

Can't send audio file with telegram bot

I've got stuck trying to get my bot to send audio file and tried reading everything I can and for some reason still not working...
this is my code, its quite long so i've just included relevant parts:
import Constants as keys
from telegram.ext import *
from telegram import ReplyKeyboardMarkup,InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery, Update
import time
import Responses as R
import song
import logging
import emoji
import random
import requests
def yes_command(update, context):
time.sleep(5)
update.message.reply_text("Let's test here, press play to listen.")
time.sleep(3)
update.message.reply_audio("press play", audio=open("C:/Users/0836/Documents/omsk/bot2/song/bootgong.mp3"))
def main():
updater = Updater(keys.API_KEY, use_context=True)
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", start_command))
dp.add_handler(CommandHandler("play", play_command))
dp.add_handler(CommandHandler("no", no_command))
dp.add_handler(CommandHandler("yes", yes_command))
dp.add_handler(MessageHandler(Filters.text, handle_message))
dp.add_handler(MessageHandler(Filters.photo, photo_command))
updater.start_polling()
updater.idle()
main()
I'm really new to bots and python so not sure what i'm doing wrong, please help! I've seen stuff about uploading it to a telegram server but not sure how?
try to add 'rb' in open
update.message.reply_audio(open("C:/Users/0836/Documents/omsk/bot2/song/bootgong.mp3", "rb"), title="press play")

discord.py bot not sending chat logs to file properly

I can't seem to make my discord.py bot send the chat logs of deleted messages to a text file correctly. It sends the logs, but it always replaces the old one instead of sending it to a new line.
import os
import discord
import time
from dotenv import load_dotenv
client = discord.Client()
TOKEN = os.getenv('DISCORD_TOKEN')
#client.event
async def on_message_delete(message):
msg = str(message.author)+ ' - '+str(message.channel)+': '+str(message.content)
with open('stats.txt', 'w') as f:
print((msg), file=f)
client.run(TOKEN)

Getting one message using the telegram python API?

I want to create a telegram bot that, after seeing the command /define, asks for the word.
I want to extract the word sent by the user after the bot asks for it. How do I do it?
import telegram
from telegram.ext import Updater
from telegram.ext import MessageHandler, Filters
from telegram.ext import CommandHandler
updater = Updater(token='******************')
dispatcher = updater.dispatcher
def define(bot, update):
bot.send_message(chat_id=update.message.chat_id, text="Enter word")
word = '''get content of following message'''
definition = get_definition(word)
bot.send_message(chat_id=update.message.chat_id, text=definiton)
definition_handler = CommandHandler('define', define)
dispatcher.add_handler(definition_handler)
updater.start_polling()
First of all, you require pyTelegramBotAPI library;
Then, you want to add #BotFather in Telegram and follow the instructure #6. You need to obtain the bot token which is a unique set of letters and digits for your bot, just like a codename. After you have registered a bot via #BotFather, it will give you the token.
Actually, the token is the only thing you need to create any bot you want. The codes for the bot like yours should follow the same logic structure:
# -*- coding: utf-8 -*-
import telebot # importing pyTelegramBotAPI library
import time
import sys
bot = telebot.Telebot(token='YOUR API TOKEN') # supply your future bot with the token you have received
#bot.message_handler(commands=['define', 'Define'])
def echo_msg(message):
echo = bot.send_message(chat_id=message.chat.it,
text='What word would you want me to extract, sir?')
bot.register_next_step_handler(message=echo, callback=extract_msg)
def extract_msg(message):
msg.append(message.text)
print(msg)
def main_loop():
bot.polling(none_stop=True)
while True:
time.sleep(1)
if __name__ == '__main__':
try:
main_loop()
except KeyboardInterrupt:
print(sys.stderr '\nExiting by user request'\n')
sys.exit(0)
Okay, each bot requires a message_handler to process the incoming information.
In your case, it is a command that triggers the bot to ask for a word to extract into a list. If you do not define bot.register_next_step_handler(), this command will not do any action at all (except the fact it asks for a word).
The function extract_msg() appends the next word written by a user and prints out the msg list into your console.
The function main_loop() runs the bot until suspension and provokes it to idle for a second after each word extraction. To stop the bot, press Ctrl + C.
I hope that suffices. The next step would be to track the person who types /define or /Define and extract his/her word request. Also, it would be better to make msg list more descriptive, or implement absolutely different extraction method. This one is simply informative and hardly applicable in practice.
I fixed an error in when calling stderr:
# -*- coding: utf-8 -*-
import telebot # importing pyTelegramBotAPI library
import time
import sys
bot = telebot.Telebot(token='YOUR API TOKEN') # supply your future bot with the token you have received
#bot.message_handler(commands=['define', 'Define'])
def echo_msg(message):
echo = bot.send_message(chat_id=message.chat.it,
text='What word would you want me to extract, sir?')
bot.register_next_step_handler(message=echo, callback=extract_msg)
def extract_msg(message):
msg.append(message.text)
print(msg)
def main_loop():
bot.polling(none_stop=True)
while True:
time.sleep(1)
if __name__ == '__main__': try:
main_loop() except KeyboardInterrupt:
print(sys.stderr('\nExiting by user request'\n'))
sys.exit(0)

Categories

Resources