Discord.py bot not running - discord

I am working on a bot and for some reason its giving me the error code of
Traceback (most recent call last):
File "main.py", line 7, in <module>
bot = commands.Bot(command_prefix='?')
TypeError: __init__() missing 1 required keyword-only argument: 'intents'
I have no idea why it isn't working I tried re-doing my code from the discord command docs. My current code is
import os
import discord
from discord.ext import commands
from replit import db
TOKEN = os.environ['TOKEN']
bot = commands.Bot(command_prefix='?')
client = discord.Client()
#bot.command()
async def echo(ctx):
await ctx.send("Welcome " + ctx.message.author.mention)
await ctx.send("Do ?commands to see all the commands")
db["money-" + ctx.message.author.id] = "0"
db["xp-" + ctx.message.author.id] = "0"
db["started-" + ctx.message.author.id] = "1"
#bot.command()
async def commands(ctx):
started = db["started-" + ctx.message.author.id]
if started == 1:
await ctx.send("--------------------")
await ctx.send("Command list")
await ctx.send("--------------------")
await ctx.send("?commands")
await ctx.send("Opens this menu")
await ctx.send("--------------------")
else:
await ctx.send("You havent ran ?start yet!")
bot.run(TOKEN)
Again I don't know much about error codes.

You need to tell which intents you want to use.
If you want to use every intent for example you have to write
bot = commands.Bot(command_prefix='?', intents = discord.Intents.all())
on line 7.
You can enable your intents on https://discord.com/developers/application choose your application and then choose Bot. If you want to use all Intents, you have to enable everything under Private Gateway Intents in order to work properly.

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,

Commands not working after updating to discord.py 2.0

I was trying to change my version from 1.7.3 to 2.0+ using pip install -U git+https://github.com/Rapptz/discord.py. Usually when I did this there would be an error about intents that would pop up, but instead there were no errors but it said:
discord.client logging in using static token
2022-12-20 12:34:14 INFO
discord.gateway Shard ID None has connected to Gateway (Session ID:6837cbf3ad28b9040ceb5e044dffe90f).
After that, any commands that I used didnt get responded to, as it worked perfectly fine in 1.7.3.
My code:
import discord, os, requests, json, random, time, datetime
from discord.ext import commands
from replit import db
import urllib
import asyncio
from discord import Member
from discord.ui import Select,Button,View
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="e!",
intents=intents)
client = discord.Client(intents=intents)
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('whats the meaning of life'):
await message.channel.send(
'The meaning of life is "freedom from suffering" through apatheia (Gr: απαθεια), that is, being objective and having "clear judgement", not indifference. - Wikipedia.'
)
time.sleep(2)
await message.channel.send(
'There, someone just explained your life. Kind of depressing, isnt it?'
)
basically you don't have the correct intents to be able to send message with the bot
you need to have the discord.Intents.all()
and please don't use the time.sleep in an asynchronous function use asycio.sleep()
import asyncio
bot = commands.Bot('e!',intents=discord.Intents.all())
#bot.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('whats the meaning of life'):
await message.channel.send(
'The meaning of life is "freedom from suffering" through apatheia (Gr: απαθεια), that is, being objective and having "clear judgement", not indifference. - Wikipedia.'
)
await asyncio.sleep(2)
await message.channel.send(
'There, someone just explained your life. Kind of depressing, isnt it?'
)

'Member' object has no attribute 'hasPermission'

i wanted to make a bot to discord for delete messages easly. it works 3 months ago but now i got an error " 'Member' object has no attribute 'hasPermission' ". thanks for everyone to share opinion. have a nice day.
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
bot = commands.Bot(command_prefix = 'botcuk')
#bot.event
async def on_ready():
await bot.change_presence(activity=discord.Streaming(name="admin biseyler deniyor", url='https://www.youtube.com/watch?v=fw7L7ZO4z_A'))
if message.content.startswith('botcuksil'):
if (message.author.hasPermission('MANAGE_MESSAGES')):
args = message.content.split(' ')
if len(args) == 2:
if args[1].isdigit():
count = int(args[1]) + 1
deleted = await message.channel.purge(limit = count)
await message.channel.send('{} mesaj silindi'.format(len(deleted)-1))
It is throwing 'Member' object has no attribute 'hasPermission' this error because 'Member' does not have an attribute named 'hasPermission'. To fix your problem, I have re-written your code and also given some explanation below the code:
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
bot = commands.Bot(command_prefix = 'botcuk')
#bot.event
async def on_ready():
await bot.change_presence(activity=discord.Streaming(name="admin biseyler deniyor", url='https://www.youtube.com/watch?v=fw7L7ZO4z_A'))
#client.event # we need to add and check for a client event
async def on_message(): # we need to execute the command when we recieve an message so we define a function called 'async def on_message():'
if message.content.startswith('botcuksil'):
if message.author.guild_permissions.manage_messages: # we need 'author.guild_permissions.(permission)' intead of 'if (message.author.hasPermission('MANAGE_MESSAGES'))'
args = message.content.split(' ')
if len(args) == 2:
if args[1].isdigit():
count = int(args[1]) + 1
deleted = await message.channel.purge(limit = count)
await message.channel.send('{} mesaj silindi'.format(len(deleted)-1))
I have not tested this yet, but according to me, your problem: 'Member' object has no attribute 'hasPermission' should be solved.
What you have done was message.author.hasPermission('MANAGE_MESSAGES') but message.author has no attribute like hasPermission.
Summary of what I have done:
I have added a client event (#client.event) and an async function on_message().
What it does is it checks if it is getting an message or not. If it detects a new message in any of the servers it is invited to, it triggers the code in on_message().
As I said: What you have done was message.author.hasPermission('MANAGE_MESSAGES') but message.author has no attribute like hasPermission.
Instead of writing that, we can use message.author.guild_permissions.manage_messages. It checks if the message author's server's permissions include "manage_messages". Hope my solution fixes your problem.
Always happy to help!
-sqd mountains

Trying to set up permissions for a discord bot but can't seem to be able to

So I'm making a discord bot for a server that I use and wanted to add a censor feature so that if a user said something in the "bannedWords" list while not in a specific channel (working) it would edit the message to have "[redacted]" in its place. I believe the code itself is working but I get this error message every time I test it. I've tried adding permissions via the Discord Developer Portal (selecting "OAuth2," choosing the "bot" scope, and the manage roles, view channels, send messages, manage messages, read message history, and mention everyone permissions), copied the link and added it to my testing server but it still didn't seem to work along with having the proper permissions via role.
Full Error:
Traceback (most recent call last):
File "C:\Users\Me\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Me\Desktop\Productive\Programming Projects\Python 3\Other\MyBot\bot.py", line 32, in on_message
await message.edit(content = editedMessage)
File "C:\Users\Me\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\message.py", line 843, in edit
data = await self._state.http.edit_message(self.channel.id, self.id, **fields)
File "C:\Users\Me\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\http.py", line 241, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50005): Cannot edit a message authored by another user
Code
import discord
bot=discord.Client()
#bot.event
async def on_ready():
print('Logged in')
print("Username: %s" % (bot.user.name))
print("Userid: %s" % (bot.user.id))
#bot.event
async def on_message(message):
if message.author.id == bot.user.id:
return
bannedWords=['chink','dyke','fag','ook','molest','nig','rape','retard','spic','zipperhead','tranny']
print(str(message))
print(str(message.content))
if "name='no-rules-lol'" not in str(message): #probably a better way to do this but it works
for word in bannedWords:
if word in message.content.lower():
await message.channel.send('{0.author.mention}, you have used a word that is black-listed please read <#754763230169006210> to get a full list of black-listed words'.format(message))
#await message.edit(content = message + 'this has been edited')
editedMessage=str(message.content.replace(word,'[redacted]'))
await message.edit(content = editedMessage)
bot.run(Token)
You cannot edit a message that is not sent by the bot.
Instead, just try deleting the message.
await message.delete()
It is as easy as that.
If you are adding more commands into your bot, you can just add this to your on_message at last:
await bot.process_commands(message)
Thank you.

NameError: name 'bot' is not defined

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")

Resources