Bot stopped working even though code is fine - python

This is my first time coding a discord bot and I have been following tutorials mainly but I wanted to make a unique game so I tried to make it myself. But after messing around with it for a while I realized that the only part of my code that works is the mcguccy is an idiot part none of the client. Command parts work.
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='!')
#client.command()
async def ping1(ctx):
await ctx.send("pong!")
#client.event
async def on_ready():
await client.change_presence(status=discord.Status.online, activity=discord.Game("cranking 90s on shitters"))
print("bot is ready!")
#client.event
async def on_member_join(member):
print(f'{member} has joined :weary:.')
#client.event
async def on_member_remove(member):
print(f'{member} has left :weary:')
#client.command()
async def helb(ctx):
await ctx.send('#everyone look at this idiot')
#client.command()
async def ping(ctx):
await ctx.send(f'here you go: {round(client.latency * 1000)}ms')
#client.command()
async def commands(ctx):
await ctx.send('1. helb it will help you. 2. ping it will tell you the bots ping. ')
#client.command()
async def overlord(ctx):
await ctx.send("muah hah hah YOUR SERVER IS MINE")
keywords = ["mcguccy is an idiot", "kick mcguccy", "i want to nuke the server"]
#client.event
async def on_message(message):
for i in range(len(keywords)):
if keywords[i] in message.content:
for j in range(20):
await message.channel.send(f"#everyone someone has spammed :weary:")

There are a few things to look at here:
Your client variable is a Bot type, not a Client type.
client = commands.Bot(command_prefix='!')
This means you need to use #bot decorators instead of #client decorators:
#client.command()
async def helb(ctx):
...
# Becomes
#bot.command()
async def helb(ctx):
...
The .run() method is never called.
Because of this, the bot's event loop doesn't start. You need to initialize the Client event loop so the bot can listen for commands to pass:
if __name__=='__main__':
client.run(TOKEN)
That code needs to be the very last statement run in the file, as it's blocking.
The .run() command requires an API token.
You can acquire said token by creating a bot account if you don't have one already. If you do have one, you'll need to pass it as the first paramater to the .run() method.

Related

Trying to make a discord bot but on.message or message.content not working

I want the bot to use the gpt-3 API to answer questions but for some reason on.message is not working
import openai
import discord
openai.api_key = "apikey"
client = discord.Client()
#client.event
async def on_ready():
print('online')
async def on_message(message):
if message.content.startswith("!ask"):
print('I read the message')
question = message.content[5:]
response = openai.Completion.create(
engine="text-davinci-002",
prompt=f"{question}\n",
temperature=0.7,
max_tokens=1024,
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
await message.channel.send(response.choices[0].text)
client.run('token')
Everything works fine and the 'online' appears but after that i don't know what's happening since i am not getting any errors (Sorry if its something obvious i am just now learning)
the
client.run('token')
open.api_key="apikey"
are obviously replaced with the real ones in my code
If you want to register an event, you have to put the client.event decorator on top of the event functions. Your on_message function certainly doesn't have one, so just put one on it.
#client.event
async def on_message(message):
...
You need to use #client.event for every event
#client.event
async def on_ready():
print('online')
#client.event # <- this is new
async def on_message(message):
# ...

A Python discord bot not responding to a command

I tried making a discord bot and stumbled across an issue, the bot does not respond to commands and I have no clue what's wrong.
Here's my code
import discord
from discord.ext import commands
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
await client.change_presence(activity=discord.Game(name="Python"))
async def on_message(self, message):
print('Message from {0.author}: {0.content}'.format(message))
await bot.process_commands(message)
client = MyClient()
client.run("Token Here")
bot = commands.Bot(command_prefix='!')
#bot.command()
async def test(ctx):
await ctx.send("Sup")
You are currently mixing a discord.Client with a commands.bot.
Discord.py provides multiples ways to creates bots that are not compatibles each other.
Moreover, client.run is blocking, and should be at the end of your script.!
import discord
from discord.ext import commands
class MyClient(commands.Bot):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
await client.change_presence(activity=discord.Game(name="Python"))
async def on_message(self, message):
print('Message from {0.author}: {0.content}'.format(message))
await self.process_commands(message)
client = MyClient(command_prefix='!')
#client.command()
async def test(ctx):
await ctx.send("Sup")
client.run("...")
Note that you are not obligated to subclass the commands.Bot class given by the library.
Here is an other exemple that don't use subclassing:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='!')
#client.event
async def on_ready():
print('Logged on as {0}!'.format(client.user))
await client.change_presence(activity=discord.Game(name="Python"))
#client.event
async def on_message(message):
print('Message from {0.author}: {0.content}'.format(message))
await client.process_commands(message)
#client.command()
async def test(ctx):
await ctx.send("Sup")
client.run("...")
Using the second approach might be beneficial if you just started to learn dpy, and can work when you dont have a lot of commands.
However, for bigger projects, the first approach will help to organise your bot by using cogs for commands and events.

Discord word filter bot doesn't delete anything

I made a discord.py bot for one of our members, as a joke. im testing it out and it doesnt work at all. can someone tell me what can be wrong with this code?
from http import client
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)
#client.event
async def on_message(message):
await client.process_commands(message) # add this if also using command decorators
if message.author.id == 300677572683890688 and "tranime" in message.content.lower():
await message.delete()
await message.channel.send(f"You are in the process of behavioural therapy. please do not attempt to bypass it, {message.author.mention}")
The structure, how you build the bot, is wrong in many ways, that could cause the error.
To run the bot,
client.run(TOKEN)
always belongs at the end of your code!
To process commands, you put
await client.process_commands(message)
at the end of your on_message event, even though this is not necessary here as you just use discord.Client().
A new structure could be:
client = discord.Client()
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
#client.event
async def on_message(self, message):
if message.author.id == 300677572683890688 and "tranime" in message.content.lower():
await message.delete()
await message.channel.send(f"Your message here")
await client.process_commands(message)
client.run(TOKEN)
The code should also be indented correctly, otherwise there may be problems.

Discord bot only responds to one command

I'm setting up a simple Python Discord bot, but it only seems to respond to one event/command. It only responds to when someone says "supreme sauce" it sends "raw sauce" but doesn't respond to anything else such as ".ping" or ".clear".
Is there anything that I'm doing wrong?
My code:
import discord
from discord.ext import commands
import time
client = commands.Bot(command_prefix = '.')
#client.event
async def on_ready():
print(f'{client.user} has successfully connected to Discord!')
#client.event
async def on_message(message):
if 'supreme sauce' in message.content:
await message.channel.send('raw sauce')
#client.command()
async def ping(ctx):
await ctx.send(f'Pong! {round(client.latency * 1000)}ms')
#client.command
async def clear(ctx, amount=10):
await ctx.channel.purge(limit=amount)
client.run('My Token')
on_message takes priority over commands.
If you want both things to happen, do like this:
async def on_message(message):
if message.author == bot.user: return #Makes sure it can't loop itself when making messages
await bot.process_commands(message)
#rest of your code here
This makes it so that when a message is sent, it will check if that message is a command and go from there, then it will execute the on_message code like normal

Discord bot commands execute multiple times

It worked at first, but then somewhy it started to give the answers 4-5 times at once, any idea why?
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '.')
#client.event
async def once_ready():
print('Bot is ready.')
#client.event
async def on_member_join(member):
print(f'{member} has joined the server.')
#client.event
async def on_member_remove(member):
print(f'{member} has left the server.')
#client.command()
async def ping(ctx):
await ctx.send('Pong!')
client.run('my token here')
So, the problem was that I couldn't shut down the already running bots in Atom.
If you add the code that I wrote down there (that only the owner can
use) will shut down the already running bots (write /shutdown in
discord server or whatever your prefix is).
However, you may need a PC restart after saving the bot with this code.
#client.command()
#commands.is_owner()
async def shutdown(ctx):
await ctx.bot.logout()
So every time if you want to edit your command, you write /shutdown
and edit it, after that, you can start it again.
I hope this works for you and that I could help if you had the same problem.

Categories