The telegram bot does not work for Persian messages - python

I create a telegram bot whit python-telegram-bot.I want to post the message to the group after sending messages to the group,and the bot check the message, and if the word in the mlist is in messages, the bot will delete the message, but if the messages are in Persian, the bot will not delete it, but if the message In Latin, the bot will delete it.Look at the messages in the mlist, when the bot sends Hello to the group, it delete it, but when the سلام sends to the group it does not delete the bot.
# -*- coding: cp1256 -*-
#!/usr/bin/python
import os, sys
from telegram.ext import Filters
from telegram.ext import Updater, MessageHandler
import re
def delete_method(bot, update):
if not update.message.text:
print("it does not contain text")
return
mlist=['Hello', 'سلام']
for i in mlist:
if re.search(i, update.message.text):
bot.delete_message(chat_id=update.message.chat_id,message_id=update.message.message_id)
def main():
updater = Updater(token='TOKEN')
dispatcher = updater.dispatcher
dispatcher.add_handler(MessageHandler(Filters.all, delete_method))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
# for exit
# updater.idle()
The bot should delete messages while sending the Persian messages in the mlist to the group, but it will not do this, but if the messages in the mlist are in Latin and will be sent to the group, messages will be deleted. . There is no error at all

First you need to debug your program to see if it reaches inside the if clause or not.
and also change the first line to:
# -*- coding: utf-8 -*-
see if it works..

Related

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

Sending a message with a python telegram bot without a command from the user?

Is there a way to send a message (call a function), without a command from the bot's user? For example when a certain condition is met?
Currently I have only been able to call a function with a command.
I have been trying the following:
from telegram.ext import Updater, CommandHandler, CallbackContext
from telegram import Update
from datetime import datetime
import telebot as tb
import logging
bot = tb.TeleBot(API_KEY)
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)
def messager(update: Update, context: CallbackContext) -> None:
"""this function messages at a specific time"""
update.message.reply_text("message back")
if __name__ == "__main__":
updater = Updater(API_KEY)
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler("message", messager))
condition = False #I have been changing this when testing
if (condition == True):
messager() # how to call messager here? how to pass update and context arguments?
updater.start_polling()
updater.idle()
Any possible way to achieve this would be great.
You cannot call a function using update and context since there is no update from the telegram servers to act on. In other words there is no event to perform a callback on.
Depending on what you want to do you could use a MessageHandler instead of a CommandHandler to reply to any message with Filters to filter out which ones to reply to
or if you want to send a message every time you start your bot and you know who to send a message to (i.e you have their chat_id) you can do
if condition:
updater.bot.send_message(chat_id=CHAT_ID, text="message back")
or if you just want to send a message every time some user starts a chat with your bot you could use the start command which is sent by default to start a chat with a bot

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

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

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