Python3 Discord Module No Attribute Client - python-3.x

I was handed a Python Discord Message Mass Prune Script in Py3.
But there were a few errors, Prior to this.
It was working before, but now it's giving me some error that
it didn't give me before.
import discord
import asyncio
client = discord.Client()
#client.event
async def on_ready():
print(' ')
print('Lorem')
print('ipsum')
print('dolor')
print('amet')
print('sit')
print('consectetur')
print('Logged in as:', client.user.name)
print('UID:',client.user.id)
print('Discord version:',discord.__version__)
print('----------')
print('Connected to:')
for server in client.servers:
print(' -',server.name)
# Define commands
#client.event
async def on_ready():
if message.author == client.user:
commands = []
z = 0
for index, a in enumerate(message.content):
if a == " ":
commands.append(message.content[z:index])
z = index+1
commands.append(message.content[z:])
# MASS DELETE OWN MESSAGES
if commands[0] == 'xc':
if len(commands) == 1:
async for msg in client.logs_from(message.channel,limit=9999):
if msg.author == client.user:
try:
await client.delete_message(msg)
except Exception as x:
pass
elif len(commands) == 2:
user_id = ''
for channel in client.private_channels:
if commands[1] in str(channel):
if str(channel.type) == 'private':
user_id = str(channel.id)
async for msg in client.logs_from(discord.Object(id=user_id),limit=9999):
if msg.author == client.user:
try:
await client.delete_message(msg)
except Exception as x:
pass
client.run("TOKEN HERE",bot=False)
Using Py3 Pip, I installed discord and asyncio (The required modules) needed for the script.
At line 4 (client = discord.Client())
It throws off the error
Traceback (most recent call last):
File "discord.py", line 1, in <module>
import discord
File "C:\Program Files\Python36\discord.py", line 4, in <module>
client = discord.Client()
AttributeError: module 'discord' has no attribute 'Client'

Your program is called discord.py. That is masking the real discord module. Call the program something else.

Change your file name from discord.py to another like discord_message.py
AS it is importing discord from your os only

Related

Discord bot isn't playing audio when commanded

I am using python 3.6
I am making a discord bot to play music.
Whenever I give it the 'play' command the discord app shows that the bot is producing audio but I don't hear any audio. I checked the settings and maximized all the audio-related settings.
When I go back to pycharm, I see this error in the 'run' tab:
Traceback (most recent call last):
File "/Volumes/Mahmoud-Disk/MyProfile/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "/Volumes/Mahmoud-Disk/MyProfile/Desktop/Discord Bot/Discord-Bot/main.py", line 72, in play
await ctx.send(embed = discord.Embed(
TypeError: __init__() got an unexpected keyword argument 'author'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Volumes/Mahmoud-Disk/MyProfile/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/Volumes/Mahmoud-Disk/MyProfile/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/Volumes/Mahmoud-Disk/MyProfile/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__() got an unexpected keyword argument 'author'
Here is my code:
import discord
from discord.ext import commands
import wavelink
client = commands.Bot(command_prefix = ".", intents = discord.Intents.all())
class CustomPlayer (wavelink.Player):
def __init__(self):
super().__init__()
self.queue = wavelink.Queue()
#client.event
async def on_ready():
client.loop.create_task(connect_nodes()) #HTTPS and Websocket operations
async def connect_nodes(): #Helper function
await client.wait_until_ready()
await wavelink.NodePool.create_node(
bot = client ,
host = "127.0.0.1" ,
port = 2333 ,
password = "yk I can't "
)
#client.event
async def on_wavelink_node_ready(node = wavelink.Node):
print(f"Node: <{node.identifier}> is ready!")
#client.command()
async def connect(ctx):
vc = ctx.voice_client
try:
channel = ctx.author.voice.channel
except AttributeError:
return await ctx.send("Please join a channel to connect.")
if not vc:
await ctx.author.voice.channel.connect(cls = CustomPlayer())
else:
await ctx.send("The bot is already connected to a voice channel.")
#client.command()
async def disconnect(ctx):
vc = ctx.voice_client
if vc:
await vc.disconnect()
else:
await ctx.send("Bot is not connected to a voice channel.")
#client.command()
async def play(ctx, *, search: wavelink.YouTubeTrack):
vc = ctx.voice_client #represents a discord voice connection
if not vc:
custom_player = CustomPlayer()
vc: CustomPlayer = await ctx.author.voice.channel.connect(cls = custom_player)
if vc.is_playing():
vc.queue.put(item = search)
await ctx.send(embed = discord.Embed(
title = search.title,
url = search.uri,
author = ctx.author,
description = f"Queued {search.title} in {vc.channel}"
))
else:
await vc.play(search)
await ctx.send(embed = discord.Embed(
title = search.title,
url = search.uri,
author = ctx.author,
description = f"Playing {vc.source.title} in {vc.channel}"))
I have no idea what to do to fix this problem.
Simply, I removed the
author = ctx.author,
That are in the "play()" command both times

client.(variable) variables in Discord.py Cogs

I am facing an issue while migrating my python code to discord.py.
The issue is, I don't know how to use client. variables in discord.py cogs like client.sniped_messages = {}...
It shows an error -
Traceback (most recent call last):
File "C:\Users\arjun\Documents\Arjun\Python\discord.py\swayde\main.py", line 55, in <module>
client.load_extension(f"cogs.{filename[:-3]}")
File "C:\Users\arjun\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\arjun\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.Utility' raised an error: NameError: name 'self' is not defined
Here's the code -
import discord
from discord.ext import commands
import random
import datetime
class Utility(commands.Cog):
def __init__(self, client):
self.client = client
self.client.sniped_messages = {}
#commands.Cog.listener()
async def on_message_delete(self,message):
self.client.sniped_messages[message.guild.id] = (message.content, message.author, message.channel.name, message.created_at)
#commands.command()
async def snipe(self, ctx):
try:
contents, author, channel_name, time = self.client.sniped_messages[ctx.guild.id]
except:
await ctx.channel.send("Couldn't find a message to snipe!")
return
embed = discord.Embed(description=contents, color=discord.Color.purple(), timestamp=time)
embed.set_author(name=f"{author.name}#{author.discriminator}", icon_url=author.avatar_url)
embed.set_footer(text=f"Deleted in : #{channel_name}")
await ctx.channel.send(embed=embed)
def setup(client):
client.add_cog(Utility(client))
Now, when I delete the variable client.sniped_messages = {}, The code runs perfectly.
Please tell me how I can resolve this issue and how to use .client variables in cogs.
Thanks in advance!
You have to indent self.client.sniped_messages = {} so it's inside the __init__ method
def __init__(self, client):
self.client = client
self.client.sniped_messages = {}

Message in a specific Discord channel

Hi guys i'm trying to make the bot send a message automatically in a specific channel. I took the channel ID and pass it in the if condition (a_string.find ('data: []')! = -1). However this code gives me this error. See OUTPU ERROR.
P.S. I'm using Replit and Live is the file name (Live.py)
from discord.ext import commands
from Naked.toolshed.shell import execute_js, muterun_js
import sys
class Live(commands.Cog):
def __init__(self,client):
self.client=client
#commands.Cog.listener()
async def on_ready(self):
channel = self.get_channel(828711580434169858)
response = muterun_js('serverJs.js')
original_stdout = sys.stdout # Save a reference to the original standard output
if response.exitcode == 0:
a_string= str(response.stdout)#stampa in console
if (a_string.find('data: []') != -1):
print("Streamer: Offline ")
else:
print("Streamer: Online")
await channel.send('Live Link: https://...link....')
else:
sys.stderr.write(response.stderr)
#commands.command()
async def Live(self,ctx):
await ctx.send('')
def setup(client):
client.add_cog(Live(client))
OUTPUT ERROR:
Ignoring exception in on_ready
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/home/runner/Solaris-IA/cogs/Live.py", line 12, in on_ready
channel = self.get_channel(828711580434169858)
AttributeError: 'Live' object has no attribute 'get_channel'
It's self.client.get_channel, not self.get_channel, you haven't defined that function
channel = self.client.get_channel(828711580434169858)

when i try to run my discord bot it tells gives me a module error

import discord
from discord.ext import commands
client = commands.bot(command_prefix = '%')
#client.command(name='scp')
async def scp(context):
mods_channel = client.get_channel(806352117442543616)
scp = discord.embed(title="scp wiki", description="http://www.scpwiki.com/scp-series", color=0xCC0000)
await context.message.channel.send(embed=scp)
#client.event
async def on_ready():
#do stuff
mods_channel = client.get_channel(806352117442543616)
await mods_channel.send('i work! ')
#client.event
async def on_typing():
mods_channel = client.get_channel(806352117442543616)
await mods_channel.send('i wonder what you are going to say :thinking:')
#client.event
async def on_message(message):
if message.content == 'hello Irantu' or message.content == 'hello irantu':
mods_channel = client.get_channel(806352117442543616)
await mods_channel.send('HI! :smile:')
#run client
Whenever I run it, it gives me TypeError: 'module' object is not callable.
this is for a discord bot that i am making for an scp themed discord server
This was all done with Visual Studio Code using Python 3.9.4.
You are trying to call discord.ext.commands.bot, which is a module. You are probably looking for discord.ext.commands.Bot:
from discord.ext import commands
client = commands.Bot(command_prefix="%")

Discordpy welcome bot

So, i tried to make a bot that send embed to specific channel everytime user join my server.
The code is look like this
import discord
import asyncio
import datetime
from discord.ext import commands
intents = discord.Intents()
intents.members = True
intents.messages = True
intents.presences = True
bot = commands.Bot(command_prefix="a!", intents=intents)
#bot.event
async def on_ready():
print('Bot is ready.')
#bot.event
async def on_member_join(ctx, member):
embed = discord.Embed(colour=0x1abc9c, description=f"Welcome {member.name} to {member.guild.name}!")
embed.set_thumbnail(url=f"{member.avatar_url}")
embed.set_author(name=member.name, icon_url=member.avatar_url)
embed.timestamp = datetime.datetime.utcnow()
channel = guild.get_channel(816353040482566164)
await channel.send(embed=embed)
and i got an error
Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\Piero\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Piero\Documents\Discord\a-chan\achan_bot\main.py", line 24, in on_member_join
channel = guild.get_channel(816353040482566164)
NameError: name 'guild' is not defined
Anyone know what is wrong in my code?
First of all, looking at the discord.py documention, ctx is not passed to the on_member_join event reference. However, you can use the attributes of member which is passed in order to get the values which you need.
#bot.event
async def on_member_join(member):
embed = discord.Embed(
colour=0x1abc9c,
description=f"Welcome {member.name} to {member.guild.name}!"
)
embed.set_thumbnail(url=f"{member.avatar_url}")
embed.set_author(name=member.name, icon_url=member.avatar_url)
embed.timestamp = datetime.datetime.utcnow()
channel = member.guild.get_channel(816353040482566164)
await channel.send(embed=embed)
Interestingly enough, you did this perfectly for getting the guild name, but it seems you forgot to do the same when retrieving channel.
You did not define guild.
To define your guild you can do the following:
guild = bot.get_guild(GuildID)
It's the same method you used to define your channel, just for your guild now.
For further information you can have a look at the docs: https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_guild
Also take into account that we do not have a paramter like ctx in an on_member_join event.
The event just has the parameter member in your case:
#bot.event
async def on_member_join(member): #Removed ctx

Resources