There is this "Traceback (most recent call last):
File "main.py", line 11, in
#client.command()
AttributeError: 'Client' object has no attribute 'command'" error coming is there something i did wrong in the code?
import os
import discord
from discord.ext import commands
from discord.ext.commands import Bot
from discord.ext.commands import has_permissions, MissingPermissions, is_owner
import json
client = discord.Client(command_prefix = ".")
status=discord.Status.idle
#client.command()
async def ban(ctx, member: discord.Member, reason=None):
await member.ban(reason=reason)
await ctx.send("member is banned")
#client.event
async def on_ready():
print('we have logged in as {0.user}'.format(client))
my_secret = os.environ['Token']
client.run(my_secret)
change client = discord.Client(command_prefix = ".")
to
client = commands.Bot(command_prefix='.')
# You have to write
# client = commands.Bot(command_prefix = '!')
# then you only write client.command() in line (11)
# And you have to also import from discord.ext import commands in line 2
import discord
from discord.ext import commands
import os
client = commands.Bot(command_prefix = '!')
#client.event
async def on_ready():
print("Bot is Online")
#client.command()
async def ping(ctx):
await ctx.send("Pong")
client.run('WRITE YOUR TOKEN HERE')
Related
I'm working on a discord bot and everything was working correctly but suddenly I got this error and I just can't figure out what should i do.
Could not prepare the client: Traceback (most recent call last): File "C:\Users\Barni\AppData\Local\Programs\Python\Python310\lib\site-packages\interactions\client\bot.py", line 444, in _ready self._intents.GUILD_PRESENCES in self._intents AttributeError: 'Intents' object has no attribute 'GUILD_PRESENCES'
here is my code:
import discord
from discord.ext import commands,tasks
import random
import interactions
import asyncio
intents = discord.Intents.default()
intents.presences = True
intents.members = True
bot = interactions.Client(token="**token**", intents=intents)
#bot.event
async def on_member_join(member):
guild = bot.get_guild(**my servers id**)
welcome_channel = guild.get_channel(**welcome channels id**)
embed = discord.Embed(title="Üdv a szerveren!", colour=discord.Colour(0x2ecc71),description=f'{member.mention}')
await channel.send(embed=embed)
suntzulist=[]
file=open("suntzu.txt","r")
for sor in file:
suntzulist.append(sor.strip())
file.close()
#bot.command(name="suntzu", description="Random Sun Tzu idézet", scope=879081332590927892)
async def suntzu(ctx: interactions.CommandContext):
await ctx.send(random.choice(suntzulist))
#bot.command(name="help", description="parancsok megmutatása", scope=879081332590927892)
async def help(ctx: interactions.CommandContext):
await ctx.send("`help` `suntzu`")
#bot.event
async def on_ready():
print('-------------')
print('Bejelentkezve')
print('-------------')
bot.start()
I tried reinstalling the interactions plugin I but got the same error.
I also tried intents.guild_presences = True but then I got this
Traceback (most recent call last): File "C:\Users\Barni\Desktop\PratBOT.py", line 10, in <module> intents.guild_presences = True AttributeError: 'Intents' object has no attribute 'guild_presences'
import discord
import os
TOKEN = 'OTUyNDkzMDk4Mjg0NTExMjQy.GSl3Un.HHDKACqLqxuM02q4Yu0eyZGfPQlgJIKhDhmq9U'
bot = UnfilteredBot(command_prefix='?')
#bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
#bot.command()
async def hello(ctx):
"""Says world"""
await ctx.send("world")
#bot.command()
async def add(ctx, left : int, right : int):
"""Adds two numbers together."""
await ctx.send(left + right)
#bot.command()
async def shutdown(ctx):
await ctx.send("shutting down")
os.system("shutdown -h now")
bot.run(TOKEN)
Traceback (most recent call last):
File "/home/pi/Desktop/app,py", line 8, in
bot = UnfilteredBot(command_prefix='?', description=description)
NameError: name 'UnfilteredBot' is not defined
These are the changes that I did in bot.py of discord bot
class UnfilteredBot(commands.Bot):
async def process_commands(self, message):
ctx = await self.get_context(message)
await self.invoke(ctx)
Error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'VoiceState' object has no attribute 'voice_channel'
Code:
from discord.ext import commands
import random
import youtube_dl
#client.command(pass_context=True)
async def join(ctx):
channel = ctx.message.author.voice.voice_channel
await client.join_voice_channel(channel)```
Try using voice.channel instead of voice.voice_channel.
from discord.ext import commands
import random
import youtube_dl
#client.command(pass_context=True)
async def join(ctx):
channel = ctx.message.author.voice.channel
await client.join_voice_channel(channel)
Also client.join_voice_channel will not work. Use something like this:
from discord.ext import commands
from discord.utils import get
import random
import youtube_dl
#client.command(pass_context=True)
async def join(ctx):
chn = ctx.message.author.voice.channel
if not chn:
await ctx.send("Error: Connect to voice channel")
return
voice = get(bot.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.move_to(chn)
I'm getting an error when trying to translate a messages' content (note that I did import the latest version of this: https://pypi.org/project/googletrans/), I've checked enough times and I think I'm doing it correctly
Full code:
import discord, googletrans, os, dotenv
from discord.ext import commands
from dotenv import load_dotenv
from googletrans import Translator
load_dotenv()
translate = Translator()
prefix = 'tb!'
bot = commands.Bot(command_prefix=prefix)
bot.remove_command("help")
client = discord.Client()
TOKEN = os.getenv('TOKEN')
#translationch = 822024643468460042
#bot.event
async def on_ready():
print(f'{bot.user.name} connected to Discord!')
await bot.change_presence(activity=discord.Game(name=f"Translating..."))
#bot.listen()
async def on_message(msg):
print(msg.content)
if msg.content == "": return
text_ = translate.translate(msg.content)
if text_.text == msg.content: return
else:
embed=discord.Embed(title="Translating...", description="Just a second...", color=0x545454)
msg = await msg.channel.send(embed=embed)
try:
emb=discord.Embed(title="Translation", color=0x00ff08)
emb.add_field(name=f"Sent by {msg.author}", value=f"`{msg.content}`\n`{text_.text}`", inline=False)
emb.set_footer(text=f"Sent from channel #{msg.channel.name}")
await msg.edit(embed=emb)
except:
i = msg.content
if i > 1800: i = "The message was too long to display!"
error=discord.Embed(color=0xff0000)
error.add_field(name="Error!", value=f"I couldn't translate **{msg.author}**'s message: `{i}`", inline=False)
await msg.edit(embed=error)
return
bot.run(TOKEN)
The error I'm getting:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\borny\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "c:/Users/borny/Desktop/stuff/vscode_projects/translate-bot/main.py", line 24, in on_message
translate.translate(msg.content)
File "C:\Users\borny\AppData\Local\Programs\Python\Python38\lib\site-packages\googletrans\client.py", line 182, in translate
data = self._translate(text, dest, src, kwargs)
File "C:\Users\borny\AppData\Local\Programs\Python\Python38\lib\site-packages\googletrans\client.py", line 78, in _translate
token = self.token_acquirer.do(text)
File "C:\Users\borny\AppData\Local\Programs\Python\Python38\lib\site-packages\googletrans\gtoken.py", line 194, in do
self._update()
File "C:\Users\borny\AppData\Local\Programs\Python\Python38\lib\site-packages\googletrans\gtoken.py", line 62, in _update
code = self.RE_TKK.search(r.text).group(1).replace('var ', '')
AttributeError: 'NoneType' object has no attribute 'group'
Ok so using this (the fixed lib) solved my problem: https://pypi.org/project/google-trans-new/
There's also an released alpha about the official googletrans lib that has this bug patched, you can find more about it in this thread: googletrans stopped working with error 'NoneType' object has no attribute 'group'
New code:
import discord, google_trans_new, os, dotenv
from discord.ext import commands
from dotenv import load_dotenv
from google_trans_new import google_translator
load_dotenv()
translate = google_translator()
prefix = 'tb!'
bot = commands.Bot(command_prefix=prefix)
bot.remove_command("help")
client = discord.Client()
TOKEN = os.getenv('TOKEN')
translationch = 822024643468460042
#bot.event
async def on_ready():
print(f'{bot.user.name} connected to Discord!')
await bot.change_presence(activity=discord.Game(name=f"Translating..."))
#bot.listen()
async def on_message(msg):
if msg.content == "": return
text_ = translate.translate(msg.content)[:-1]
if text_ == msg.content: return
else:
embed=discord.Embed(title="Translating...", description="Just a second...", color=0x545454)
msg_ = await msg.channel.send(embed=embed)
try:
emb=discord.Embed(title="Translated!", color=0x00ff08)
emb.add_field(name=f"Sent by {msg.author}", value=f"`Text: {msg.content}`\n`Translation: {text_}`", inline=False)
await msg_.edit(embed=emb)
except:
i = msg.content
if len(i) > 1800: i = "The message was too long to display!"
error=discord.Embed(color=0xff0000)
error.add_field(name="Error!", value=f"I couldn't translate **{msg.author}**'s message: `{i}`", inline=False)
await msg_.edit(embed=error)
return
bot.run(TOKEN)
I've recently tried to create a simple bot in discord with Python Code.
I'm testing just the first features to DM a user when he joins the server
Here is my code:
import os
import discord
from dotenv import load_dotenv
load_dotenv() #load .env files
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
client = discord.Client()
#client.event
async def on_ready():
guild = discord.utils.get(client.guilds, name=GUILD)
print(
f'{client.user} has connected to the following guild:\n'
f'{guild.name}(id: {guild.id})'
) #debug
members = '\n - '.join([member.name for member in guild.members])
print(f'Guild Members:\n - {members}') #debug
#client.event
async def on_member_join(member):
await member.creat_dm()
await member.dm_channel.send(
f'Hi {member.name}, welcome to my Discord Server!'
)
client.run(TOKEN)
Ignoring exception in on_member_join
Traceback (most recent call last):
File "/home/andre/.local/lib/python3.8/site-packages/discord/client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "/home/andre/repos/github/discord_project/bot.py", line 30, in on_member_join
await member.creat_dm()
AttributeError: 'Member' object has no attribute 'creat_dm'
Can anyone help me with this annoying bug?
I've seen articles that show member.create_dm() being used
You are right, there is a member.create_dm() https://discordpy.readthedocs.io/en/latest/api.html?highlight=create_dm#discord.Member.create_dm
But you spelled it wrong "member.create_dm()"
You may try to store the DM channel into a variable, so you can call it later.
(Just my opinion on making the code better)
#client.event
async def on_member_join(member):
dmChannel = await member.create_dm()
await dmChannel.send(f'Hi {member.name}, welcome to my Discord Server!)
The answer posted is correct but you should not call create_dm()frequently, member.send() works the most time.
Docs: create_dm()
#client.event
async def on_member_join(member):
await member.send(f'Hi {member.name}, welcome to my Discord Server!)