Cannot Host Discord Bot on repl.it - python

I recently made a discord bot and ran in on repl.it as it has free hosting (I use uptime robot). But, when I run main.py the uptime robot says that the website that I use for keep_alive() is "Down" and when I try to access the website from my browser it doesn't load either saying that the site "can't be reached". When I close the repl.it tab my bot goes offline as well.

Repl.it is not made for hosting discord bot's it's prone to rate limits.
It's good for writing code online and hosting basic web apps or collaborating with others while coding.
You should definitely invest in a proper host like PebbleHost, PloxHost and etc if you need something to write code online. However, a VPS provider like Linode, Digitalcoean or even PloxHost would be more beneficial as you have your own dedicated IP and are not affected by rate limits from other users. However, this does require knowledge of Linux.
For your issue of your keep_alive you should try this:
from flask import Flask
from threading import Thread
import time
app = Flask('')
#app.route('/')
def home():
return "Hello World!"
def run():
app.run(host='0.0.0.0',port=8080)#127.0.0.1 or ::
def keep_alive():
t = Thread(target=run)
t.start()
Then in your main.py:
from keep_alive import keep_alive
keep_alive()

You should take a look at UptimeRobot to send pings to the URL of the web server associated with the repl. This video is for node.js but should apply to python as well on the UptimeRobot chunk

Related

Access WhatsApp messages from the day using API

I am building an application using the WhatsApp Business Cloud API. Essentially I want to know if it's possible to build an application that collects all the messages from the day and downloads it. Specifically the media attached to it using the API. As far as I know you can use webhooks to get incoming messages. But in order to do this the application has to be run forever, and my cousin has a problem with this as it could cause problems to run an application forever vs just run it once a day. I'm able to send messages using the API and a python wrapper but that's much more simple than what I'm trying to do. Aditionally, there is an option of using selenium but that's not really an automated solution to what we're trying to do because everytime selenium executes the browser we'd need to log in using the QR code. If anyone has any idea if this is possible (or not possible) I'd be very appreciative!
from heyoo import WhatsApp
import logging
import requests
from dotenv import load_dotenv
from flask import Flask, request, make_response
app = Flask(__name__)
token = 'EAAVk5rqOCsABAAcPPrZC6GnlZAJuykdFIQd4DhkuRVNeGntfFOU5jaK4jG2yCZBS6i7kFQGk3kRvDP0fExBXRsFyqWUqfVVJsSxeQdcA9XHWpRuUsnnuwqLcZAQpwTiuoZCXv4ixCcHYlPEe6NGHupCalHvWw9NQRoZAVnegU5ZCBvX6eO9E8vyum1lQ2SSt7OuUpdpIkmkyBK8tiEL8rpGwM8RrqZA3A10ZD'
messenger = WhatsApp(token, phone_number_id='100398242927044')
messenger.send_message('Hey its JJ ', '1xxxxxxxx')
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
print("hello")
#app.route("/", methods=["GET", "POST"])
def hook():
//some code that isn't working yet
I'm new to all of this stuff so I don't really know how to set up a webhook either but my cousin who's business I'm building this app for doesn't ideally want to use a webhook.
You can use ngrok server, which provides:
how to use ngrok to integrate your localhost app with WhatsApp by using Webhooks. WhatsApp webhooks can be used to notify an external application whenever specific events occur in your WhatsApp account
https://ngrok.com/docs/integrations/whatsapp/webhooks

How can I get my code running 24/7 on replit without it only working once and then my bot also not working?

I made code for my discord bot and used UptimeRobot to keep it running constantly but then it my bot just stopped working randomly and I'm not sure why. It worked once and maybe ran for a few hours and now it completely won't work, even if I get rid of the 'keep_alive' code.
UptimeRobot - https://uptimerobot.com Discord Bot Tutorial - https://www.youtube.com/watch?v=SPTfmiYiuok | Time - 58:47
Main:
[Start of code]
import os
import random
import discord
from keep_alive import keep_alive
[ALL MY CODE/COMMANDS]
Then at the end of is this [my commands] ---->
keep_alive()
my_secret = os.environ['TOKEN']
client.run[my_secret]
[NEW FILE-KEEP_ALIVE.PY]
from flask import Flask
from threading import Thread
app = Flask('')
#app.route('/')
def home():
return "Hello. I am alive!"
def run():
app.run(host='0.0.0.0',port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
You should not use free hosting services, they are usually really bad. You should get a paid one (you not need to spend money on it and get premium servers) you can try amazon aws free trail. it should be enough for the discord bot and run 24/7 for 12 months. Other than that, if you need more ressouces you can find a hosting provider, register with a virtual creditcard, order the stuff you like and freeze the vcc. a good vcc provider is revolut.

Only script apps may use password auth praw

I'm trying to make a Reddit reposter but every time I run the program it says
"prawcore.exceptions.OAuthException: unauthorized_client error processing request (Only script apps may use password auth)"
def bot_login():
print('Logging in...')
r = praw.Reddit(username='**',
password='**',
client_id='**',
client_secret='**',
user_agent='None')
print('Logged in as user: "'+str(r.user.me())+'"')
print("------------------------------------------------------------------")
return r
any idea on how to fix it?
You probably made a web app on the reddit applications page on accident. Reddit only allows script type web applications to use password authentication for security purposes.
To Fix:
Go to https://www.reddit.com/prefs/apps
Choose the "script" type application
(picture)
Recreate your application

How to deploy a Python Telegram Bot to Azure without using Flask?

I create a Telegram bot using Python, here is the code:
TOKEN = BOT TOKEN
# deploy
def run(updater):
PORT = int(os.environ.get('PORT', '8443'))
updater.start_webhook(listen="0.0.0.0",
port=PORT,
url_path=TOKEN)
updater.bot.set_webhook("Azure WEB APP URL".format(TOKEN))
def start_handler(bot, update):
do something
def callback_func(bot, job):
do something
def trigger_callback(bot, update, job_queue):
logger.info("User {} trigger bot".format(update.effective_user["id"]))
bot.send_message(chat_id=update.message.chat_id, text='Starting!')
job_queue.run_repeating(callback_sql, 600, context=update.message.chat_id)
def stop_callback(bot, update, job_queue):
logger.info("User {} stop bot".format(update.effective_user["id"]))
bot.send_message(chat_id=update.message.chat_id,
text='Stoped!')
job_queue.stop()
if __name__ == '__main__':
logger.info("Starting bot")
updater = Updater(TOKEN)
updater.dispatcher.add_handler(CommandHandler('start', start_handler))
updater.dispatcher.add_handler(CommandHandler('trigger', trigger_callback, pass_job_queue=True))
updater.dispatcher.add_handler(CommandHandler('stop', stop_callback, pass_job_queue=True))
run(updater)
I have test the Bot in local and it run perfectly. So now how can I deploy it to the Azure Cloud??? Thank guys for you helping!!!
I see the introduction about Azure Bot Service but don't know how to do!
It's actually pretty easy:
Install azure cli, then create a requirements.txt file in the root of your python app with the libraries you need. For example:
python-telegram-bot>=13.3,<=13.3
Open Powershell or Bash, depending on your OS, and run
az webapp up -n <app-name> -g <rg-name> --sku <your-sku> --location <your-location>
A few notes:
Name the main file app.py so that Azure will run it automatically
Configure Always On on your app service in Configuration -> General Settings. This will always keep the bot running. Otherwise Azure will turn it off when idle and only restart it when the website is requested. As your bot works in pull mode, it will never be restared again unless you do it manually, so you need the Always On feature. You'll need a B1 or App Service Plan or better, the free plan does not support Always On.

Flask streaming doesn't work on my machine

Related to this question.
I'm trying to use Flask streaming and having difficulty doing so, it seems my example works on any machine I try it on other than my own. I'm running Flask 0.10.1, Werkzeug 0.9.4, and Python 2.7.6. I have reinstalled Flask and Werkzeug with no effect. If someone could suggest a way to debug this I would be very grateful.
The problem I experience is that data doesnt get sent to the client while the stream is open, it is only sent once the stream is closed (eg in the example below when the generator function returns).
#!/usr/bin/env python
from flask import Flask, Response
from time import sleep
def stream():
n = 10
while n > 0:
yield "data: hi\n\n"
sleep(0.5)
n = n - 1
app = Flask(__name__)
#app.route("/events")
def streamSessionEvents():
return Response(
stream(),
mimetype="text/event-stream"
)
#...also has a route to output html/js client to consume the above
app.run(threaded=True)
Revisited this recently, it was indeed the virus scanner messing with my network traffic.
I'm using Sophos, and found that if I add the address of the machine hosting my Flask application to the virus scanner's "allowed sites" list then my SSE events are received correctly.

Categories

Resources