I am trying to make the bot leave a server with the ID, Command !leave
I get the error 'Bot' object has no attribute 'get_server'
Here is my script:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='!')
token = TOKEN HERE
#client.command()
async def leave(ctx, ID):
toleave = client.get_server(ID)
await client.leave_server(toleave)
print("Left Server")
client.run(token)
Since, discord.py 1.1, get_server has been renamed to get_guild, and leave_server has been moved to Guild.leave. So, your code would look something like:
toleave = client.get_guild(ID)
await toleave.leave()
This should work
#commands.command()
async def leave(self, ctx, *, message=None ):
guild_id = message
guild = await self.client.get_guild(int(guild_id))
channel = guild.system_channel
await channel.send("Leaving this server due to misuse!")
await guild.leave()
Related
i want to make a discord bot but i cant run it.
idk what to do
it just runs
and no log
idk REALLY what to do
import discord
from discord.ext import commands
import os
import keep_alive
client = commands.Bot(command_prefix="!")
token = os.environ.get('Token')
GUILD = os.environ.get('Guild')
async def on_ready():
print(f'{client.user} is connected')
#client.command()
async def dm(ctx, member: discord.Member):
await ctx.send('what do u want to say bitch!')
def check(m):
return m.author.id == ctx.author.id
massage = await client.wait_for('massage', check=check)
await ctx.send(f'send massage to {member} ')
await member.send(f'{ctx.member.mention} has a massage for you: \n {massage}')
#client.event
async def on_member_join(member):
channel = discord.util.get(member.Guild, name='general')
await channel.send(f'Hey welcome to my server {member.mention}, hope you enjoy this server!')
keep_alive.keep_alive()
client.run(token)
client.close()
i dont know what to do anymore
I tried everything i could i ran it in pycharm
vscode
nothing works
There's a lot of errors on your code. so I fixed it
First thing is your client events, keep_alive, client.run, also why did you put client.close()
import os, discord
import keep_alive
from discord.ext import commands
client = commands.Bot(command_prefix="!")
token = os.environ.get('Token')
GUILD = os.environ.get('Guild')
#client.event # You need this event
async def on_ready():
print(f'{client.user} is connected')
"""
client.wait_for('massage') is invalid. Changed it into 'message'. Guess it is a typo.
You can replace this command with the new one below.
"""
#client.command()
async def dm(ctx, member: discord.Member):
await ctx.send('what do u want to say bitch!')
def check(m):
return m.author.id == ctx.author.id
massage = await client.wait_for('message', check=check)
await ctx.send(f'send massage to {member} ')
await member.send(f'{ctx.member.mention} has a massage for you: \n {massage}')
"""
I also moved this on_member_join event outside because it blocks it.
"""
#client.event
async def on_member_join(member):
channel = discord.util.get(member.Guild, name='general')
await channel.send(f'Hey welcome to my server {member.mention}, hope you enjoy this server!')
"""
I put the keep_alive call outside because the function blocks it in your code.
And also removed client.close() to prevent your bot from closing
"""
keep_alive.keep_alive()
client.run(token)
For the dm command. Here it is:
#client.command()
async def dm(ctx, member:discord.Member=None):
if member is None:
return
await ctx.send('Input your message:')
def check(m):
return m.author.id == ctx.author.id and m.content
msg = await client.wait_for('message', check=check) # waits for message
if msg:
await member.create_dm().send(str(msg.content)) # sends message to user
await ctx.send(f'Message has been sent to {member}\nContent: `{msg.content}`')
Sorry, I'm kinda bad at explaining things, also for the delay. I'm also beginner so really I'm sorry
Code:
import os
import discord
import random
from discord.ext import commands
GUILD = os.getenv('DISCORD_GUILD')
client2 = commands.Bot(command_prefix = '')
#client.event
async def on_ready():
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} has connected to '
f'{guild.name}'
)
#client.event
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
bot = commands.Bot(command_prefix='$')
#client2.command(pass_context = True)
async def mute(ctx, member: discord.Member):
if ctx.message.author.server_permissions.administrator or ctx.message.author.id == '194151340090327041':
role = discord.utils.get(member.server.roles, name='Muted')
await bot.add_roles(member, role)
embed=discord.Embed(title="User Muted!", description="**{0}** was muted by **{1}**!".format(member, ctx.message.author), color=0xff00f6)
await bot.say(embed=embed)
else:
embed=discord.Embed(title="Permission Denied.", description="You don't have permission to use this command.", color=0xff00f6)
await bot.say(embed=embed)
client.run(os.getenv('TOKEN'))
I am trying to create a bot that mutes people. This is my 1st week in learning the discord API. I copied the mute function from a website so I didn't code everything myself. I'm having some trouble with the command. The error is:
NameError: name 'commands' is not defined
But I have seen other people do this and not get an error so I have no idea what the problem is.
Thanks a lot!
As mentioned before, you are going around with definitions that don't exist/that you shouldn't use.
First: Decide between client or bot and use the original handling, not somehow client2 etc.
Second: To use the commands, import from discord.ext import commands.
Third: Since you are now using client the commands have to be adapted. Also you don't use client.say or bot.say anymore, but ctx.send.
Fourth: You can't use multiple on_ready events, combine them or just use one.
Fifth: Please have a look at the mute command as yours contained many errors and requested things in the wrong way. You can take a look at other StackOverflow questions and answers as just copy and pasting another answer is not really useful...
Have a look at the full/final code:
from discord.utils import get # New import
import discord
from discord.ext import commands # New import
client = commands.Bot(command_prefix = 'YourPrefixHere') # Changes
TOKEN = "YourTokenHere" # Changes
#client.event
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
#client.command()
async def mute(ctx, member: discord.Member):
if ctx.message.author.guild_permissions.administrator or ctx.message.author.id == 'Your_ID': # Changes
role = discord.utils.get(ctx.guild.roles, name='Muted') # Changes
await member.add_roles(role)
embed = discord.Embed(title="User Muted!",
description="**{}** was muted by **{}**!".format(member, ctx.message.author),
color=0xff00f6)
await ctx.send(embed=embed)
else:
embed=discord.Embed(title="Permission Denied.", description="You don't have permission to use this command.", color=0xff00f6)
await ctx.send(embed=embed)
client.run(TOKEN) # Changes
I'm wondering how to send a message to a specific channel in discord.
Here's the code I have so far:
import discord
client = discord.Client()
#client.event
async def on_ready():
channel = client.get_channel(channelID)
await channel.send('hello')
client.run("---")
I want to have is so you run a command like !channel, and for that specific guild, the channel ID is set under the channelID variable. It has to be like this because if there are multiple servers, the admins can set where the message is sent.
So far, I found this post, but it's for javascript: Set channel id for DiscordBot for multiple servers
Here's the updated code:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='$')
client = discord.Client()
main_channels = {}
#bot.command()
async def channel(ctx):
guild_id = ctx.guild.id
channel_id = ctx.channel.id
main_channels[guild_id] = channel_id
await channel.send('hi')
client.run("TOKEN")
Any help is appreciated!
The command you're trying to implement is very simple; just create a dictionary that associates the guild's ID with the ID of the channel in which to send the message:
bot = commands.Bot(command_prefix = "$")
main_channels = {}
# The following command associates the ID of the guild to that of the channel in which this command is run.
#client.command()
async def channel(ctx):
guild_id = ctx.guild.id
channel_id = ctx.channel.id
main_channels[guild_id] = channel_id
# The following command sends a greeting message to the main channel set earlier for this guild.
#client.command()
async def greet(ctx):
guild_id = ctx.guild.id
channel_id = main_channels[guild_id]
channel = ctx.guild.get_channel(channel_id)
await channel.send("hi")
bot.run(token)
However, I suggest you consider using a permanent data archive, either an offline file (such as a json) or a real database, because once the bot is disconnected it is no longer possible to retrieve the data stored in that dictionary.
If you want to send the message to a specific channel, you have to do this:
import discord
client = discord.Client()
#client.event
async def on_ready():
print('Online')
#client.event
async def on_message(message):
if message.content == "!channel":
channel = client.get_channel(SPECIFIC CHANNEL ID)
await channel.send("Hello")
client.run('TOKEN')
Else, if you want your bot to response in the same channel as the message, you can do this:
import discord
client = discord.Client()
#client.event
async def on_ready():
print('Online')
#client.event
async def on_message(message):
if message.content == "!channel":
await message.channel.send("Hello")
client.run('TOKEN')
Good afternoon! I am new to Python , and I am working on a discord bot. I keep suffering from this error: AttributeError: 'Client' object has no attribute 'command'. I tried everything to repair this, but I did not know. Any help would be fine. Please help me!
Here is the code:
import discord
import random
from discord.ext import commands
class MyClient(discord.Client):
client = commands.Bot(command_prefix = '?')
# Start
async def on_ready(self):
print('Logged on as', self.user)
# Latency
client = discord.Client()
#client.command()
async def ping(ctx):
await ctx.send(f'Pong! {round(client.latency * 1000)}ms')
# 8ball
#client.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
responses = ['Biztosan.',
'Nagyon kétséges.']
await ctx.send(f'Kérdés: {question}\nVálasz: {random.choice(responses)}')
# Clear
#client.command()
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)
await ctx.send(f'Kész!')
async def on_message(self, message):
word_list = ['fasz', 'kurva', 'anyad', 'anyád', 'f a s z', 'seggfej', 'buzi', 'f.a.s.z', 'fa sz', 'k U.rv# any#dat']
if message.author == self.user:
return
messageContent = message.content
if len(messageContent) > 0:
for word in word_list:
if word in messageContent:
await message.delete()
await message.channel.send('Ne használd ezt a szót!')
messageattachments = message.attachments
if len(messageattachments) > 0:
for attachment in messageattachments:
if attachment.filename.endswith(".dll"):
await message.delete()
await message.channel.send("Ne küldj DLL fájlokat!")
elif attachment.filename.endswith('.exe'):
await message.delete()
await message.channel.send("Ne csak parancsikont küldj!")
else:
break
client = MyClient()
client.run(token)
There are a multitude of ways to make your bot, and it seems you tried to mash 2 ways of making it together.
Option 1: using the pre-made commands bot class
client = commands.Bot(command_prefix = '?')
client.command()
async def command_name(ctx, argument):
#command function
client.run(token)
Option 2: making you own subclass of client
class MyClient(discord.Client):
async def on_message(self, message):
if message.content.startswith('command_name'):
#command functionality
client = MyClient()
client.run()
You can use either of the two options, but not both at the same time (you could actually do that, but not in the way you did)
Also I would advice staying away from discord.py to learn python as asyncio is pretty complex
Why don't you simply define client like this?
client = commands.Bot(...)
Also you have defined it a couple of times in the code, delete them all and define it only ONCE at the top of the code after the imports. This is a really bad question, you should learn a lot more python before diving deeper into discord.py.
I am trying to make a discord bot using Python and I want to make it so not everyone can mention #everyone or when they do the message will be deleted immediately, but then I have another code ($snipe) which doesn't work until I delete it, and after I do, it gives me the response! Any help would be appreciated!
#client.event
async def on_message(message):
xall = "#everyone"
role1 = discord.utils.get(message.guild.roles, name = "Owner")
role2 = discord.utils.get(message.guild.roles, name="Mod")
roles = role1 or role2
if xall in message.content:
if roles in message.author.roles:
pass
else:
await message.delete(message)
#Fun
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#client.command()
async def snipe(ctx):
await ctx.send("Aight, imma go snipe!")
#client.command()
async def slap(ctx, members: commands.Greedy[discord.Member], *, reason='no reason'):
slapped = ", ".join(x.mention for x in members)
await ctx.send('{} just got slapped for {}'.format(slapped, reason))
import discord
from discord.ext import commands
client = discord.Client()
#client.event
async def on_message(msg):
owner = discord.utils.get(msg.guild.roles, name="Owner")
mod = discord.utils.get(msg.guild.roles, name="Mod")
roles = (owner, mod)
if msg.mention_everyone:
if not any(r in msg.author.roles for r in roles):
await msg.delete()
client.run(TOKEN)
I have just ran this, and this works as expected. Removes the message if needed.