Code hangs when trying to run code, telegram bot deployment - python

I am trying to compile some python code and run it as a telegram bot.
When I run it on VS Code or in the CMD console (python main.py) it freezes.
However, when I broke up the code individually and run, it works well.
1) Can any PyGod point out where im doing wrong?
2) I realised this happens when I try to redeploy a telegram bot too. Anyone have ideas on this?
from telegram.ext import Updater, InlineQueryHandler, CommandHandler
from telegram.ext.dispatcher import run_async
import requests
import re
def get_url():
contents = requests.get('https://dog.ceo/api/breed/retriever/golden/images/random').json()
url = contents['message']
return url
def get_image_url():
allowed_extension = ['jpg','jpeg','png']
file_extension = ''
while file_extension not in allowed_extension:
url = get_url()
file_extension = re.search("([^.]*)$",url).group(1).lower()
return url
#run_async
def goodboy(update, context):
url = get_image_url()
chat_id = update.message.chat_id
context.bot.send_photo(chat_id=chat_id, photo=url)
def main():
updater = Updater('YOUR_TOKEN', use_context=True)
dp = updater.dispatcher
dp.add_handler(CommandHandler('goodboy',goodboy))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()

Related

Use PYROGRAM method result in FASTAPI

I'm very nooby in python and async/await operations are very complicated for me in this language :(
I wanna create small REST api app that response Telegram chat members information by chatId.
This is my small console app, i ran it with parameters and after that parse output with another language, but when I'm using it, I'm receiving FLOOD_WAIT exception after several trys, so I should hold the connection open.
import argparse
from pyrogram import Client
argParser = argparse.ArgumentParser()
argParser.add_argument("-apiid", help="Telegram api_id")
argParser.add_argument("-apihash", help="Telegram apihash")
argParser.add_argument("-token", help="Telegram bot token")
argParser.add_argument("-groupid", type=int, help="Telegram group id")
args = argParser.parse_args()
app = Client("my_account", args.apiid, args.apihash, bot_token=args.token)
app.start()
async def spy(groupId):
result = []
async for member in app.get_chat_members(groupId):
print(member)
print(",")
print("---BEGIN---")
app.run(spy(args.groupid))
print("---END---")
I'm tried to make the same via FASTAPI but I didn't successed :( Please help me, what should I do with function result?
tgapp = Client("my_account", api_id, api_hash, bot_token=telegramToken)
tgapp.start()
app = FastAPI()
#app.get("/{chatId}")
async def index(chatId):
res = tgapp.get_chat_members(chatId)
#WHAT SHOULD I DO WITH RES???
return res
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8002)

DeepAI API error - {"err": "error processing given inputs from request"}

I'm a noobie at Python and was just messing around, but now I'm really curious why it isn't working. I'm currently trying to build a telegram bot that generates an image based on the text given to the bot. I think there might be a problem with my DeepAI api? When I click this link: https://api.deepai.org/api/text2img i always get the error
{"err": "error processing given inputs from request"}
. The bot is linked but gives me the error as in the code below. My code below:
import requests
import json
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
def text_to_image(update, context):
# Get the text from the user
text = update.message.text
# Set up the DeepAI API request
api_key = "{{ api }}"
headers = {
"api-key": api_key
}
data = {
"text": text
}
# Make the request to the DeepAI API
response = requests.post("https://api.deepai.org/api/text2img", headers=headers, json=data)
if response.status_code != 200:
update.message.reply_text("An error occurred while generating the image. Please try again later.")
return
# Get the generated image from the response
response_json = response.json()
image_url = response_json["output_url"]
# Send the generated image to the user
context.bot.send_photo(chat_id=update.effective_chat.id, photo=image_url)
def main():
# Set up the Telegram bot
updater = Updater(token="{{ api }}", use_context=True)
dispatcher = updater.dispatcher
# Add the text_to_image handler
text_to_image_handler = MessageHandler(Filters.text, text_to_image)
dispatcher.add_handler(text_to_image_handler)
# Start the bot
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
I've tried changing code and different things but nothing seems to work, i'm really stuck right now
From the looks of it, it's an error on the API side of things. The status code of the API server depends on traffic and account/key.
Things to do:
Check if your API key is valid and wait when server works on google, then try to run your code

Reply to a Python Telegram bot message

Please tell me how you can call the bot's response to any message in the feedback bot. By example:
User: /start
Bot: Welcome message (Hello)
User: any message
Bot: Feedback message (Expect an answer)
I tried to do it through the echo function, but most likely I made a mistake somewhere.
I am attaching the code:
main.py:
from telegram.ext import Updater
from handlers import setup_dispatcher
from settings import TELEGRAM_TOKEN
# Setup bot handlers
updater = Updater(TELEGRAM_TOKEN)
dp = updater.dispatcher
dp = setup_dispatcher(dp)
updater.start_polling()
updater.idle()
settings.py:
import os
from dotenv import load_dotenv, find_dotenv
# Loading .env variables
load_dotenv(find_dotenv())
TELEGRAM_TOKEN = "HERE TELEGRAM TOKEN"
TELEGRAM_SUPPORT_CHAT_ID = "HERE CHAT ID"
TELEGRAM_SUPPORT_CHAT_ID = int(TELEGRAM_SUPPORT_CHAT_ID)
WELCOME_MESSAGE = os.getenv("WELCOME_MESSAGE", "Hi ๐Ÿ‘‹")
FEEDBACK_MESSAGE = os.getenv("FEEDBACK_MESSAGE", "Expect an answer๐Ÿ‘‹")
REPLY_TO_THIS_MESSAGE = os.getenv("REPLY_TO_THIS_MESSAGE", "REPLY_TO_THIS")
WRONG_REPLY = os.getenv("WRONG_REPLY", "WRONG_REPLY")
handlers.py:
import os
from telegram import Update
from telegram.ext import CommandHandler, MessageHandler, Filters, CallbackContext
from settings import WELCOME_MESSAGE, TELEGRAM_SUPPORT_CHAT_ID, REPLY_TO_THIS_MESSAGE, WRONG_REPLY
def start(update, context):
update.message.reply_text(WELCOME_MESSAGE) # response to /start
user_info = update.message.from_user.to_dict()
context.bot.send_message(
chat_id=TELEGRAM_SUPPORT_CHAT_ID,
text=f"""
๐Ÿ“ž Connected {user_info}.
""",
)
def echo(update: Update, context: CallbackContext):
update.message.reply_text(FEEDBACK_MESSAGE) # there should be a response to any message "Expect an answer"
def forward_to_chat(update, context):
forwarded = update.message.forward(chat_id=TELEGRAM_SUPPORT_CHAT_ID)
if not forwarded.forward_from:
context.bot.send_message(
chat_id=TELEGRAM_SUPPORT_CHAT_ID,
reply_to_message_id=forwarded.message_id,
text=f'{update.message.from_user.id}\n{REPLY_TO_THIS_MESSAGE}'
)
def forward_to_user(update, context):
user_id = None
if update.message.reply_to_message.forward_from:
user_id = update.message.reply_to_message.forward_from.id
elif REPLY_TO_THIS_MESSAGE in update.message.reply_to_message.text:
try:
user_id = int(update.message.reply_to_message.text.split('\n')[0])
except ValueError:
user_id = None
if user_id:
context.bot.copy_message(
message_id=update.message.message_id,
chat_id=user_id,
from_chat_id=update.message.chat_id
)
else:
context.bot.send_message(
chat_id=TELEGRAM_SUPPORT_CHAT_ID,
text=WRONG_REPLY
)
def setup_dispatcher(dp):
dp.add_handler(CommandHandler('start', start))
dp.add_handler(MessageHandler(Filters.chat_type.private, forward_to_chat))
dp.add_handler(MessageHandler(Filters.chat(TELEGRAM_SUPPORT_CHAT_ID) & Filters.reply, forward_to_user))
return dp
I will be very grateful for your help
Thanks to Aditya Yadav for the advice :)
Additionally, I researched the documentation, regarding the dialog handler part of the library I use. The following solution was found:
Rewrite the def echo and def forward_to_chat functions, combining them.
def echo_forward_handler(update, context):
text = 'Expect an answer'
context.bot.send_message(chat_id=update.effective_chat.id,
text=text)
forwarded = update.message.forward(chat_id=TELEGRAM_SUPPORT_CHAT_ID)
if not forwarded.forward_from:
context.bot.send_message(
chat_id=TELEGRAM_SUPPORT_CHAT_ID,
reply_to_message_id=forwarded.message_id,
text=f'{update.message.from_user.id}\n{REPLY_TO_THIS_MESSAGE}'
)
The necessary dispatcher was also formed at the end:
def setup_dispatcher(dp):
dp.add_handler(MessageHandler(Filters.text & (~Filters.command) & Filters.chat_type.private, echo_forward_handler))
return dp
Thus, the task that was set in the condition was solved.

Get updates only one time per message

Im building a Telegram bot using the official API and python with the requests lib
I`ve add a command named text, that return "example text" when it is called. Until here all ok, but the bot only send a response when the python script is executed
So I do that the script execute indefinitely with a white True condition.
The problem is that if I execute indefinitely the script it will be making requests all the time to the API, so if I check the last message all the time with the script, the last message will be /text until I write another message.
How can do that the function that read the command will execute only one time when a new command will requested?
The code is the next:
# TELEGRAM BOT USING THE API
import requests as req
from dotenv import load_dotenv
from pprint import pprint
import re
import os
config = load_dotenv(".env")
teletoken = os.environ.get("telegram_token")
uri = f"https://api.telegram.org/bot{teletoken}/"
# Dynamic Telegram API method
def method(method):
return f"{uri}{method}"
# Response to a command
def get_and_response(chat_id: str or int):
updates = req.get(method("getUpdates"))
response = updates.json()
command_regex = re.findall("^/text*", response["result"][-1]["message"]["text"])
if command_regex == ["/text"]:
req.post(method("sendMessage"), data={"chat_id": chat_id, "text": "Example text"})
if __name__ == "__main__":
while True:
get_and_response(*chat_id*)

How to get the message id telegram channel from my bot and remove that message?

hi and thanks for your answer. i want to create a bot for forward message to my channel and delete the last message every 1 minute
i made that but i have some problem for removing the last message. i cant get the last message id from my channel to the bot.
my source is:
from telegram.bot import Bot
from telegram.update import Update
from telegram.ext.updater import Updater
from telegram.ext.callbackcontext import CallbackContext
from telegram.ext.messagehandler import MessageHandler
from telegram.ext.filters import Filters
from telegram.chataction import ChatAction
from time import sleep
import telegram_send
import socket
import telegram
import json
api_key="My API Key"
user_id = "My User Id"
updater = Updater(api_key, use_context=True)
bot = telegram.Bot(token=api_key)
def echo(update: Update, context: CallbackContext):
context.bot.send_chat_action(chat_id=update.effective_chat.id, action=ChatAction.TYPING)
sleep(60)
if update.message['photo'] == []:
bot.send_message(chat_id=user_id, text=update.message.text)
else:
fileID = update.message['photo'][-1]['file_id']
context.bot.sendPhoto(chat_id = user_id,caption=update.message['caption'],photo = fileID)
msg_id = update.message._id_attrs[]
#------------- And Also i user that too -------------
#msg_id=update.message.message_id
#------------- -------------
context.bot.delete_message(chat_id=user_id, message_id=msg_id)
update.effective_chat
update.effective_user
update.effective_message
print(json.dumps(update.to_dict(), indent=2))
dp = updater.dispatcher
dp.add_handler(MessageHandler(Filters.document | Filters.photo, echo))
dp.add_handler(MessageHandler(Filters.text, echo))
updater.start_polling()
and when i use that code this error will show:
The message_id that you want to remove is not exist....
actually i type a message id in manually for delete message and it was work
but i want to delete that message auto
please help me to do that. thanks
I fixed That With Python-Telegram-Bot Version 20
Read This Docs:
https://docs.python-telegram-bot.org/en/v20.0a2/

Categories

Resources