NameError: name 'bot' is not defined - discord

I'm currently developing a discord bot and ran into an issue where the word bot isn't 'defined'.
I've already tried replacing bot with client, however, that creates more issues.
This is my code:
#bot.command()
async def kick(ctx, user: discord.Member, * , reason=None):
if user.guild_permissions.manage_messages:
await ctx.send('I cant kick this user because they are an admin/mod.')
elif ctx.author.guild_permissions.kick_members:
if reason is None:
await ctx.guild.kick(user=user, reason='None')
await ctx.send(f'{user} has been kicked by {ctx.message.author.mention}')
else:
await ctx.guild.kick(user=user, reason=reason)
await ctx.send(f'{user} has been kicked by {ctx.message.author.mention}')
else:
await ctx.send('You do not have permissions to use this command.')

You need to create an instance of bot for it to run correctly:
import discord
from discord.ext import commands
bot = discord.ext.commands.Bot(command_prefix = "your_prefix");
bot.run("your_token")

Related

Why wont my discord bot recognise commands?

I'm trying to make a discord bot that will provide the current price of crypto currencies when a command (!price) is used, below is my code i have taken out my bots token for obvious reasons
import requests
from discord import Client, Intents
intents = Intents.default()
intents.members = True
client = Client(intents=intents)
#client.event
async def on_ready():
print(f'Logged in as {client.user}')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!price'):
symbol = message.content[6:].upper()
url = f'https://api.coingecko.com/api/v3/simple/price?ids={symbol}&vs_currencies=usd'
print(f'Fetching price for symbol: {symbol}')
response = requests.get(url)
print(f'API response: {response.json()}')
print(f'response.status_code: {response.status_code}')
try:
price = response.json()[symbol]['usd']
await message.channel.send(f'The price of {symbol} is ${price}')
except KeyError:
print(f'Error: Symbol {symbol} not found')
await message.channel.send(f'Error: Symbol {symbol} not found')
client.run('TOKEN GOES HERE')
i have tried literally everything, Ive added so many debugging tools and I'm fairly certain that the problem lies with my bot picking up my commands in the discord server,

Discord.py autorole issue

I'm new at programming.I want to create an autorole system in my Discord server.I tried this:
class MyClient(discord.Client):
async def on_member_join(member):
server = client.get_guild(serverid)
role = server.get_role(roleid)
await member.add_roles(role)
But it's not working.Thanks for helping.
This works for me so I guess this will be useful for you:
import discord
from discord.ext import commands
from discord.utils import get
client = commands.Bot(command_prefix='!', intents=discord.Intents.all())
#client.event
async def on_ready():
print(f'{client.user} Started!')
#client.event
async def on_member_join(member: discord.Member):
role_id = 1234567890123456
role = get(member.guild.roles, id=role_id)
await member.add_roles(role)
client.run('your bot token here')
role_id is Integer.
must have member intents turned on, if you don't know how to enable read this:
Here

Making my discord bot listen for specific messages and answer back when it identifies one

So, I'm new to python and even more to coding bots on discord. At the moment I'm using discord.py and red-bot (https://docs.discord.red/en/stable/index.html).
At the moment I'm trying to make the bot listen to a new message and print something in response to it, but I just can't figure it out. Since I'm using red-bot I didn't go through the steps of using client = discord.Client() and setting a token on the code itself so using #client.event() doesn't seem to work, nor #bot.event(), and I can't really find any other way to make the bot listen for an on_message() event.
Edit with part of my code:
import discord
from discord.ext import commands
from redbot.core import commands
class MyCog(commands.Cog):
client = discord.Client()
def __init__(self, bot):
self.bot = bot
#bot.event()
async def on_message(self, message):
if 'test' in message.content:
await self.send_message(message.channel, 'it works!')
Console returns that bot in #bot.event() is not defined.
Also a separate initialization file, it's done this way to follow Red's guide of how to make a cog.
from .remind import MyCog
def setup(bot):
bot.add_cog(MyCog(bot))
Here is an example of a cog that replies to a specific word mentioned. It also has a cooldown to prevent the bot spamming which I find absolutely neccesary to include.
from curses.panel import bottom_panel
import discord
from discord.ext import commands
class brilliant(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._cd = commands.CooldownMapping.from_cooldown(1, 60.0, commands.BucketType.member) # Change accordingly
# rate, per, BucketType
def ratelimit_check(self, message):
"""Returns the ratelimit left"""
bucket = self._cd.get_bucket(message)
return bucket.update_rate_limit()
#commands.Cog.listener()
async def on_message(self, message):
if message.author == self.bot.user:
return
msg = message.content.lower()
brilliant = ['brilliant', 'Brilliant', 'brilliant!', 'Brilliant!']
if any(word in msg for word in brilliant):
retry_after = self.ratelimit_check(message)
if retry_after is None:
await message.channel.send("Brilliant!")
await self.bot.process_commands(message)
else:
return
async def setup(bot):
await bot.add_cog(brilliant(bot))
If you want it in the main file, you can put something a lot simpler:
brilliant = ['brilliant', 'Brilliant', 'brilliant!', 'Brilliant!']
#bot.event
async def on_message(message):
if message.author == bot.user:
return
msg = message.content.lower()
if any(word in msg for word in brilliant):
await message.channel.send("Brilliant!")
await bot.process_commands(message)
Hope it helps.

Discord.py Ban all discord issue

I created a ban all discord command by using a few tutorials on stack overflow but the problem is the bot attempts to ban itself and prioritizes that first, making the bot completely not work, any suggestions? Here's my code:
async def ban(ctx):
guild = ctx.message.guild
for member in ctx.guild.members:
try:
await member.ban(reason="Banned")
print(f"Banned {member.display_name}!")
except:
print(f"Could not ban {member.display_name}")
async def ban(ctx):
guild = ctx.message.guild
for member in ctx.guild.members:
if member.id == bot.user.id:
continue
try:
await member.ban(reason="Banned")
print(f"Banned {member.display_name}!")
except:
print(f"Could not ban {member.display_name}")
This code makes the bot continue the loop if the member is itself

Trying to use ack and getingg ban from discord Why?

Code:
import discord
token = 'mytoken'
client = discord.Client()
#client.event
async def on_ready():
print("Online!")
for guild in client.guilds:
print(guild)
await guild.ack()
client.run(token, bot=False)
I am Getting ban from discord every time i using this
The owner of this website (discordapp.com) has banned you temporarily from accessing this website.
Because you sends more than normal human requests-per-second.
You can try to fix it with await asyncio.sleep() but I suggest you just stop using selfbots.
Possible fix:
#client.event
async def on_ready():
print("Online!")
for guild in client.guilds:
print(guild)
await guild.ack()
await asyncio.sleep(10) # Sleep for 10 seconds

Resources