Run discord bot/client from another file - python

How can i have bot code in one file but run the actual bot in another file (not cogs/extensions).
i need to run it in another file because of loop conflicts.
i tried importing client (variable of the bot constructor) and .start() on it but it didnt work, only the web server started.
example code:
in bot file:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="!")
#client.event
async def on_ready():
print("Im ready!")
in another file (Sanic web app in my case):
from bot_file import client
import discord
from sanic import Sanic
app = Sanic()
app.run()
client.run("token")

I have cool solution for you
why Don't you make only 1 file that have all the code like this
import discord
import requests
import json
client = discord.Client()
def get_quote():
response = requests.get("https://zenquotes.io/api/random")
json_data = json.loads(response.text)
quote = json_data[0]['q'] + " -" + json_data[0]['a']
return(quote)
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('inspire'):
quote = get_quote()
await message.channel.send(quote)
client.run('TOKEN')

Related

Python Discord Bot is Posting to Multiple GroupMe Groups

I am running a Python Multiple bot server with Pebblehost. My bot reads a Discord channel and posts the message from that channel into GroupMe. I'm using this bot in multiple servers. Bot 1 is suppose to post from DiscordA to GroupMeA. Bot 2 is suppose to post from Discord B to GroupMeB. However, when I post in DiscordA, my bots are posting to both GroupMeA and GroupMeB.
Here is the code I'm using for 'main.py':
import os
import discord
import aiohttp
from dotenv import load_dotenv
load_dotenv()
DISCORD_TOKEN = os.getenv('DISCORD_TOKEN')
GROUPME_BOT_ID = os.getenv('GROUPME_BOT_ID')
CHANNEL_WEBHOOK_URL = os.getenv('CHANNEL_WEBHOOK_URL')
client = discord.Client(intents=discord.Intents.all())
endpoint = f'https://api.groupme.com/v3/bots/post?bot_id={GROUPME_BOT_ID}'
async def post(message):
payload = {'text': f'{message.content}'}
async with aiohttp.ClientSession() as session:
async with session.post(endpoint, json=payload) as response:
print(await response.json())
#client.event
async def on_message(message):
if message.webhook_id == CHANNEL_WEBHOOK_URL:
return await post(message)
#client.event
async def on_ready():
print('Bot is ready')
client.run(DISCORD_TOKEN)
I also have an '.env' file with:
DISCORD_TOKEN=''
GROUPME_BOT_ID=''
CHANNEL_WEBHOOK_URL=''
and a requirements.txt file:
discord.py==1.6.0
aiohttp==3.7.3
python-dotenv==0.15.0

Discord bot in python- message not sending

Below is the current code. I'm kinda new to python, but my previous bot with virtually the same code ran perfectly fine, so i don't understand why it's not running. The bot will turn on and show as "online" in Discord, but won't send the message.
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = 'token'
client = discord.Client(intents=discord.Intents.all())
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
async def on_message(message):
channel = message.channel
content = message.content
user = message.author
userid = message.author.id
if content == "hello":
await client.send_message(channel, "rude response")
client.run(TOKEN)
For your code to work you need to add a decorator to every method.
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = 'token'
client = discord.Client(intents=discord.Intents.all())
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
# You forgot decorator here
#client.event
async def on_message(message):
channel = message.channel
content = message.content
user = message.author
userid = message.author.id
if content == "hello":
await client.send_message(channel, "rude response")
client.run(TOKEN)
on_message here is not decorated with #client.event hence you just define a function and never call it. Add the decorator to make a listener out of it
#client.event
async def on_message(message):
...

Discord Bot to Count How Many Times 'bruh' is Said

So this is my code:
import discord
from discord.ext import commands
import discord.utils
import os
import json
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
counters = load_counters()
if "bruh" in message.content:
counters["bruh"] += 1
await message.channel.send(str(counters["bruh"]))
save_counters(counters)
def setup(client):
client.add_cog(Message_Counter(client))
client.run(os.getenv('TOKEN'))
But every time I run it and test it with the bot in discord, it says that 'load_counters' is not defined. Also, I am using the website repl.it and have the token saved as a secret key. I have the counter for how many 'bruh's there are in a json file with the code:
{
"bruh": 0,
}

Python discord Bot coping messages from one user and sending them in a webhook

So I tried writting a bot that will copy messages from one user and send them in a webhook to a different server but I got stuck on coping the message and can't find any answers.
import discord
import os
import requests
import json
from dhooks import Webhook, file
hook = Webhook("WEBHOOK HERE")
client = discord.Client()
#client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
async def on_message(message):
if message.author.id == "ID HERE":
hook.send(content = "MESSAGE HERE", username = "Secound", avatar_url = "https://i.imgur.com/Kg5IIib.png")
client.run(os.getenv('TOKEN'))
discord.Message has the attribute content that refers to the content of the message
content = message.content
# i.e `Hello world`
Reference:
Message.content

Improper token passed

I'm following a basic tutorial for a Python Discord bot on YouTube and my code is underneath. It says:
discord.errors.LoginFailure: Improper token has been passed.
Before anyone asks, yes I have put in the bot token, not the id or secret.
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
Client = discord.Client()
client = commands.Bot(command_prefix = "!")
#client.event
async def on_ready():
print("Bot is ready!")
#client.event
async def on_message(message):
if message.content == "cookie":
await client.send_message(message.channel, ":cookie:")
client.run("token is here")
For me, my bot.py file looks like this:
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)
and since I used env (environment) modules, I created a new file with an empty name and with the .env extension in the same path in a folder. The env file only has this line of code:
DISCORD_TOKEN=DFHKJAhka7fdsKHJASDFk1jhaf5afd.HASDFafd23FHdfa_adfahHJKADF32W
So the problem for me was I was using brackets around the token code and after I removed it, it worked!
My code when it had brackets:
DISCORD_TOKEN={DFHKJAhka7fdsKHJASDFk1jhaf5afd.HASDFafd23FHdfa_adfahHJKADF32W}
Make sure you grab the "Token" from the "Bot" page in the Discord development site, rather than the "Secret" from the "General Information" page.
I was having the same problem. My issue was solved by using the correct token from the Discord app page. I was using the "Secret" from the 'General Information' page (which generated the error in the original post for me) instead of the "Token" from the "Bot" page.
As sheneb said in the comment to this, this answer (probably) won't help the OP (since the question now says "Before anyone asks, yes I have put in the bot token, not the id or secret"). However, I found this question/page when searching for the answer, and my issue was solved with this information.
The same thing happened to me, but it started working when I went to the developer page and refreshed the token. Then I just put the new token in the code and it worked!
Maybe the same will work for you...?
You should be able to get it to work by doing this:
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
Client = discord.Client()
client = commands.Bot(command_prefix = "!")
#client.event
async def on_ready():
print("Bot is ready!")
#client.event
async def on_message(message):
if message.content == "cookie":
await message.client.send(":cookie:")
client.run("token is here", bot=True)
I do this sometimes, but also, check to make sure you have fully created your bot by taking a look at the "bot" tab on your developer page.
I also made a fix for your message send line. It was out of date ;).
Try this:
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
Client = discord.Client()
client = commands.Bot(command_prefix = "!")
#client.event
async def on_ready():
print("Bot is ready!")
#client.event
async def on_message(message):
if message.content == "cookie":
await message.client.send(":cookie:")
client.run("TOKEN HERE. PUT YOUR TOKEN HERE ;)")
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
Client = discord.Client()
client = commands.Bot(command_prefix = "!")
#client.event
async def on_ready():
print("Bot is ready!")
#client.event
async def on_message(message):
if message.content == "cookie":
await message.client.send(":cookie:")
client.run("PUT YOUR TOKEN HERE")

Categories