I have these two files:
main.py
import os
import discord
from keep_alive import keep_alive
client = discord.Client()
my_secret = os.environ['Token']
async def SendMeMessage():
user = await client.fetch_user('my id')
await user.create_dm()
await user.dm_channel.send("Someone needs help")
keep_alive()
client.run(my_secret)
keep_alive.py
from flask import Flask
from threading import Thread
#from main import SendMeMessage
app = Flask('')
#app.route('/')
def home():
#SendMeMessage()
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()
And I would like to import SendMemessage. So when someone send get request on flask server, I wanna receive message from my discord bot. I'm stuck on error "circular import", when I implement commented code.
I would move the discord bot code out of main.py, so it no longer depends on an import of keep_alive.
bot.py:
import os
import discord
client = discord.Client()
async def SendMeMessage():
user = await client.fetch_user('my id')
await user.create_dm()
await user.dm_channel.send("Someone needs help")
keep_alive.py:
from flask import Flask
from threading import Thread
from bot import SendMeMessage
app = Flask('')
#app.route('/')
def home():
SendMeMessage()
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()
main.py:
import os
from keep_alive import keep_alive
from bot import client
my_secret = os.environ['Token']
keep_alive()
client.run(my_secret)
This way, bot.py has already been fully imported when keep_alive.py runs, so there is no longer a circular import.
Related
I wanted to make a bot which will send a fact every day (I took some code from there). But there is a problem. My bot sends same message every day. Why it doesn't work properly?
import os
import time
import discord
import json
from discord.ext import commands
from datetime import datetime, time, timedelta
import bilgiler_sözlüğü
from server import server
server()
TOKEN = os.environ['bot_token']
client = discord.Client()
sira = 1
def zaman():
print("Zaman komutu çalıştırıldı.")
while True:
current_time = datetime.now().strftime("%H:%M")
if current_time == "05:45":
global sayac
print("Zaman eşleştirildi.")
break
zaman()
#client.event
async def on_ready():
global sira
print("{0.user}".format(client), "çalıştırıldı.")
channel = client.get_channel(1001947725635530805)
try:
await channel.send(bilgiler_sözlüğü.sözlük[sira])
sira += 1
except KeyError:
await channel.send("Bilgilerim bitti!")
client.run(TOKEN)
"sira" is the variable which pulls out my dictionary. It must increase day by day. What must I do?
My bot is working now. For wonderers, its code:
import os
import time
import discord
import json
from discord.ext import commands
from datetime import datetime, time, timedelta
import bilgiler_sözlüğü
from server import server
server()
TOKEN = os.environ['bot_token']
client = discord.Client()
bugün = datetime.now().strftime("%d:%m")
#client.event
async def on_ready():
print("{0.user}".format(client), "çalıştırıldı.")
channel = client.get_channel(1001947725635530805)
try:
await channel.send(bilgiler_sözlüğü.sözlük[bugün])
except KeyError:
await channel.send("Bilgilerim bitti!")
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("/gbbilgi"):
await message.channel.send("**Günün Bilgisi**, her gün saat 00:00'da kanalınıza bir bilgi gönderen bir bottur.\n\n**Yapıcı:** Ajan Smith#4747")
client.run(TOKEN)
server.py:
from flask import Flask
from threading import Thread
app = Flask('')
#app.route('/')
def home():
return '<h1>Günün Bilgisi</h1>'
def run():
app.run(host='0.0.0.0',port=8080)
def server():
t = Thread(target=run)
t.start()
#Source: https://gist.github.com/beaucarnes/51ec37412ab181a2e3fd320ee474b671
I'm hosting a python discord bot on Replit.com 24/7 with a hacker plan.
Is there a way to make the bot DM me when the code stops running by any reason?
I've tried the atexit and signal function but it's not doing anything when I stop the code. Here's the code:
import atexit
import signal
async def handle_exit():
user = await getUserByID(my_ID)
await user.send(f"{bot.user} is offline! :x:")
atexit.register(handle_exit)
signal.signal(signal.SIGTERM, handle_exit)
signal.signal(signal.SIGINT, handle_exit)
#discord code here
Any other way than DM on discord is okay too, as long as I get notified when the bot goes offline.
Thank you in advance.
ok, so u have to add an file with flask server :
from threading import Thread
from itertools import cycle
from flask import Flask
app = Flask('')
#app.route('/test')
def main():
return "Your Bot Is Ready"
#app.route('/')
def lol():
return "Your Bot Is Ready"
def run():
app.run(host="0.0.0.0", port=8080)
def keep_alive():
server = Thread(target=run)
server.start()
and then import that file in ur main.py or bot file and then add file_name.keep_alive()
and then make a new bot and use following code:
from discord.ext import commands
import requests
bot = commands.Bot(prefix="!")
#client.event
async def on_ready():
channel = bot.get_channel()
while True:
r = requests.get("url that u get on bar of replit")
if r.status_code != 200:
await channel.send("bot is offline")
bot.run("token of another bot")
and to get url
I have a small discord bot and a small flask project (bot.py and app.py).
On my flask project I have an endpoint that I can receive JSON POST request (i can see the JSON fine). Now the question is how do I send from Flask to my Bot.py this JSON payload so that my bot.py posts it on my Discord channel.
My code:
flask app:
from flask import Flask, json, request,
app = Flask(__name__)
#app.route('/', methods=['GET'])
def index():
return 'working ...'
#app.route('/webhook', methods=['POST'])
def jiraJSON():
if request.is_json:
data = request.get_json()
print(data)
return 'json received', 200
else:
return 'Failed - Not a JSON', 400
if __name__ == '__main__':
app.run()
my bot.py from (https://realpython.com/how-to-make-a-discord-bot-python/)
# bot.py
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
client = discord.Client()
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
client.run(TOKEN)
So I've managed to make it work using Quart and a bot with Discord.py.
This will take a JSON on a webhook and send that JSON to a Discord bot to be posted on a Chanel ID.
import discord
import asyncio
from quart import Quart, request
app = Quart(__name__)
client = discord.Client()
# Setup for Discord bot
#app.before_serving
async def before_serving():
loop = asyncio.get_event_loop()
await client.login('<<<your_discord_bot_token_id>>>')
loop.create_task(client.connect())
#Setup for webhook to receive POST and send it to Discord bot
#app.route('/webhook', methods=['POST'])
async def myJSON():
channel = client.get_channel(<<<your_discord_chanel_ID>>>)
if request.is_json:
data = await request.get_json()
print(data)
await channel.send(data)
return 'json received', 200
else:
return 'Failed - Not a JSON', 400
if __name__ == '__main__':
app.run()
I run this, it connects however when running it will not return anything when it comes to commands. I've tried changing this to the context return method from on every message. Previously only one message would appear, now none with this method even though both commands are the same with slight differences. What is my error on this? Sorry this is literally my first attempt at a discord bot.
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
botToken = os.getenv("DiscBotToken")
discClient = discord.Client()
bot = commands.Bot(command_prefix = "!")
#discClient.event
async def on_ready():
print(f"{discClient.user} is now connected.")
print('Servers connected to:')
for guild in discClient.guilds:
print(guild.name)
#bot.command(name = "about")
async def aboutMSG(ctx):
aboutResp = "msg"
await ctx.send(aboutResp)
#bot.command(name = "test")
async def testMSG(ctx):
testResp = "msg"
await ctx.send(testResp)
discClient.run(botToken)
You heading in the right direction commands.Bot have both event and command no need to use a client just for events.
You should either use discord.Client or commands.Bot not both in your case it is commands.Bot.
Also you are running the client only
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
botToken = os.getenv("DiscBotToken")
bot = commands.Bot(command_prefix = "!")
#bot.event
async def on_ready():
print(f"{discClient.user} is now connected.")
print('Servers connected to:')
for guild in discClient.guilds:
print(guild.name)
#bot.command(name = "about")
async def aboutMSG(ctx):
aboutResp = "msg"
await ctx.send(aboutResp)
#bot.command(name = "test")
async def testMSG(ctx):
testResp = "msg"
await ctx.send(testResp)
bot.run(botToken)
im trying to Import commands from another PY file. But it always Says command not exists...
This is my code in the file named test.py
from discord import Embed
from random import choice
from colorama import *
from os import path
from plyer import notification
intents = discord.Intents().all()
client = commands.Bot(command_prefix = ">", intents=intents)
#commands.command()
async def haha(ctx):
await ctx.send("hi")
import customcmd
client.run("censored")
The code in customcmd.py is
import discord
from discord.ext import commands, tasks
#commands.command()
async def hi(ctx):
await ctx.send(hi)#
Try this
from .customcmd import *