Python-Telegram bot running locally, but not on Heroku - heroku

I'm looking to deploy my python-telegram bot on Heroku but the bot seems to be unresponsive. The .py works just fine locally, but when I deploy it the app builds perfectly and is on, but produces no response on telegram when prompted. The code is very basic but I think I am missing something with the webhook maybe? I'm new to web stuff as my background is more in data science. Below is my code and procfile.
"""import telegram
from telegram.ext import Updater
from telegram.ext import CommandHandler
import ftx
client = ftx.FtxClient()
telegram_bot_token = "token"
updater = Updater(token=telegram_bot_token, use_context=True)
dispatcher = updater.dispatcher
def start(update, context):
chat_id = update.effective_chat.id
context.bot.send_message(chat_id=chat_id, text= "1 ***=" + "$" + str(client.get_market('***/USD')['last']) + "\n" + "24 Change =" + str(round(client.get_market('***/USD')['change24h'],2)*100) + "%" + "\n" + "24 Hour Volume =" + str(client.get_market('***/USD')['volumeUsd24h']) + "USD"
+ "\n"*2 + "The information presented by the price tracker is not meant to be taken as financial advice.")
#I think over here I need something else
dispatcher.add_handler(CommandHandler("***", start))
updater.start_polling()"""
#Proc
"""worker: python bot.py"""
I'm happy to write a if dunder main, but I'm unsure still if I even need a webhook. Thanks!

AFAIK Heroku doesn't support long polling, so you should use a webhook. python-telegram-bot comes with a built-in webhook. See here and also this skeleton-repo.

Related

How to make my telegram-bot multi-threading?

I have a trouble. I need make my telegram-bot multi-threading. My bot will help users to buy films and will work with database. I use Webhooks-method for receiving requests from Telegram-server and Stripe(module request). I read a lot about threading module in python and about async functions but I am not sure for all 100% about how to make my bot multi-threading. I will very appreciated for help, because I am stuck on this question.
For now I give you main function of my app, if you need more, tell me:
#app.route('/', methods=["POST"])
def process():
print(request.json) # receiving requests (messages) in json format that are sent to the Flask server from the Telegram server and Stripe
if check_if_successful_payment(request) == True:
# Processing a request from Stripe
# chat_id = request.json["data"]["object"]["metadata"]["chat_id"]
stripe.api_key = get_from_env("PAYMENT_TOKEN")
webhook_list = stripe.WebhookEndpoint.list()
chat_id = webhook_list.data[0].metadata.chat_id
send_message(chat_id, "The payment was successful! Enjoy watching the movie!")
print("The payment was successful!")
webhook_id = webhook_list.data[0].id
stripe.WebhookEndpoint.delete(
webhook_id,
)
else:
# Processing a request from Telegram
chat_id = request.json["message"]["chat"]["id"]
send_message(chat_id, check_message(chat_id, request.json["message"]["text"]))
send_pay_button(chat_id=chat_id, text="Test payment",
price_id=check_price_id(request.json["message"]["text"]))
return {"ok": True}
if __name__ == '__main__':
app.run(debug=True)
If your bot works on Webhooks, you can use Aiogram instead of Flask for receiving messages from users. Aiogram has special decorator for simultaneous messages processing from many users - async_task: https://docs.aiogram.dev/en/latest/_modules/aiogram/dispatcher/dispatcher.html#Dispatcher.async_task

how to add an image to user playing activity?(discord.py)

Iam trying to add image user activity status in discord.py and basically, the problem is that I can't seem to add an image so I looked up discord.py API but couldn't find how to do it. So if you know do answer.
Would like to know how to add one. (NOT FOR BOTS)
Here is the code
import discord, os, keep_alive, datetime
import discord.ext
from discord.ext import tasks
intents = discord.Intents.default()
client = discord.Client()
launch_time = datetime.datetime.utcnow()
#client.event
async def on_ready():
print("Account Activated")
print(launch_time)
if not Status_loop.is_running():
Status_loop.start()
Put it in a loop to constantly update the activity
#tasks.loop(seconds=1, count=None, reconnect=True)
async def Status_loop():
delta_uptime = datetime.datetime.utcnow() - launch_time
hours, remainder = divmod(int(delta_uptime.total_seconds()), 3600)
minutes, seconds = divmod(remainder, 60)
days, hours = divmod(hours, 24)
print(f"Online Time: {days:02d}d | {hours:02d}h | {minutes:02d}m | {seconds:02d}s")
await client.change_presence(status = discord.Status.dnd,
activity = discord.Activity(type=discord.ActivityType.playing,
large_image = "https://i.imgur.com/Kk2BvJg.jpg",
large_text = "This is Game Icon",
name = "Sleeping Simulatorđź’¤",
details = "Dreams of Desires(Easy)",
state = f"{days:02d}d | {hours:02d}h | {minutes:02d}m Passed"))
Here is the Status on a user account
If you are wondering why I am even doing this, well I just wanted a custom status
It seems that after trying sites and other kinds of ways to do it, I finally got it using replit uploaded file link... and it worked...
large_image = "https://e8a593e1-79cc-4f08-9992-2b588af90e7f.id.repl.co/static/sleepingface.jpg",
large_text = "This is Game Icon",
small_image = "https://e8a593e1-79cc-4f08-9992-2b588af90e7f.id.repl.co/static/sleepingface.jpg",
small_text = "This is Game Icon",
The result:

The file in Heroku can not be modified

I just deploy a python app in a free Heroku server. This python app provides a telegram bot to me. I want the bot to modify the userconfig.json which is in the same directory with main.py. When I test my bot in my local machine, it works well, the userconfig.json can be modified, but when app deploys on Heroku, it can't modify the file. After sending the modify order, there is no change on my userconfig.json. How can I solve this problem?
Below is the member method which modifies the json file
def modify_token(self, new_token):
self.tokenArray[0] = new_token
token_update = [{'token': self.tokenArray[0]}]
try:
with open("./userconfig.json", 'w') as config:
json.dump(token_update, config)
except Exception as e:
return False
return True
And I use these codes to ask telegram bot to modify the file
def modify(update: Update, context: CallbackContext):
# print(context)
print(context.args)
try:
user_cake.modify_token(context.args[0])
except Exception as e:
err_res = str(e)
context.bot.send_message(chat_id=update.effective_chat.id, text="An error occurred:" + err_res)
else:
context.bot.send_message(chat_id=update.effective_chat.id, text="Your new token is: " + user_cake.tokenArray[0])

How to select a button from a interactive message with a bot?

I'm trying to get a bot to "click" a button on an interactive message in Slack (preferably as a bot, but using a user token works too).
I've found that the link to send the action information to be
https://blue-hybrid.slack.com/api/chat.attachmentAction
My problem is I can't find any documentation for "chat.attachmentAction." Looking at the request sent when using my browser, it has one http argument: "_x_id" and the payload is a WebKitForm, containing 4 items: payload, client_id, payload_id, and token.
I'm sure if I'm just not sending the appropriate data or authentication or what. All of my POSTs return "invalid_payload" or "invalid_arg_name."
Any help is greatly appreciated.
Looks like I figured it out, finally!
I had to work it out the old fashioned way. Slack Customer Support would only help with the official public API. I'll leave the solution here in Javascript.
To do this, you need 3 things:
choice_num
the number of the choice within the list of options.
e.g. If a message has the buttons (from left to right): yes, no, and maybe, then yes=0, no=1 and maybe=2.
message
the json of the interactive message
SLACK_TOKEN
your slack token (not sure if bot tokens work, user tokens do however)
The method chat.attachmentAction itself requires 3 arguments:
payload
service_id AND/OR bot_user_id
token
args = encodeURI(
'payload={'
+ '"actions":[' + JSON.stringify(message.attachments[0]["actions"][choice_num]) + '],'
+ '"attachment_id":"' + message.attachments[0]["id"] + '",'
+ '"callback_id":"' + message.attachments[0]["callback_id"] + '",'
+ '"channel_id":"' + message.channel + '",'
+ '"message_ts":"' + message.ts + '"}'
+ '&service_id=' + message.bot_id
+ '&bot_user_id=' + message.user
+ '&token=' + SLACK_TOKEN
)
request_url = 'https://YOURSLACKTEAM.slack.com/api/chat.attachmentAction?' + args
then just send an async POST to the request_url and you should get back something like this:
{"replaced":true,"ok":true}

How to send feed back information to server via my application?

In my application feedback form will be used .i have to send feedback information to server.please help me how to send information to server in windows phone.
You could use the EmailTask:
var emailTask = new EmailComposeTask
{
To = "feedback#mycompany.com",
Subject = subjectTextBox.Text,
Body = String.Format("Dear {0},/nPlease let {1}" +
" know that I would like to {2}.\nThis " +
"has been bothering me for {3} days now. " +
"I hope you can help me out. Kindest " +
"regards,\n{4}\n", toTextBox.Text,
nameTextBox.Text, activityTextBox.Text,
daysTextBox.Text, senderTextBox.Text)
};
emailTask.Show();
or you could publish a web service or you could have a web page that you point the WebBrowser control to.
It all depends on the way you want to receive the feedback and (perhaps) continue the conversation.

Resources