How to get the bot's voice state? - python

I want to create a discord.py bot that can mute and unmute itself. But I dont know how to get the VoiceState of the bot.
import discord, asyncio
from discord.ext import commands
bot = commands.Bot(command_prefix="/")
#bot.command()
async def unmute(ctx):
voice_client=ctx.guild.voice_client
channel=voice_client.channel
if ???ctx.channel.guild.voice_state???(channel=channel, self_deaf=True):
await ctx.channel.guild.change_voice_state(channel=channel, self_deaf=False)
await ctx.send("Unmuted!")
return
else:
await ctx.send("Error! Not muted!")
return

You need intents.voice_states enabled.
intents = discord.Intents.default() # enabling everything apart from privileged intents (members and presences)
bot = commands.Bot(command_prefix='/', intents=intents)
reference
Also, it's not ctx.channel.guild.voice_state(...), it's ctx.guild.voice_client or ctx.voice_client

Related

How to make a custom discord.py bot embed?

I've been trying to make the bot send embeds but it's just not working, the code is executed with no errors but the embed doesn't get sent in the channel
#client.command()
async def embed(ctx):
embed=discord.Embed(
title='Title',
description='Description',
color=0x774dea
)
await ctx.send(embed=embed)
I already had the Privileged Gateway Intents enabled, but i added the intents to the code, same problem. Here is the full code:
import discord
from discord.ext import commands
from discord import Intents
_intents = Intents.default()
_intents.message_content = True
TOKEN = 'MYTOKENISHERE'
client = commands.Bot(command_prefix='$', intents=_intents)
#client.event
async def on_ready():
print('We Have logged in as {0.user}'.format(client))
#client.command()
async def embed(ctx):
embed=discord.Embed(
title='Title',
description='Description',
color=0x774dea
)
await ctx.send(embed=embed)
client.run(TOKEN)
It seems like you may not have the correct Discord Intents enabled for your bot.
Here may be a fix for your issue:
Go to the Discord Developer Portal and enable the options listed under Bot -> Privileged Gateway Intents
Note: If your bot reaches over 100 servers, you'll be required to apply for each of these
Image: here
Replace your current commands.Bot instantiation with something like this (focus on the _intents and intents=_intents portions):
from discord import Intents
from discord.ext import commands
_intents = Intents.default()
# Enable or disable the intents that are required for your project
_intents.message_content = True
bot = commands.Bot(command_prefix='*', intents=_intents)
# code here
bot.run(your_token_here)
If you're curious about customization of Intents and what you can do with them, read more here.

discord.py on_member_join() isn't working

beforehand: I tried already a lot of potential fixes which are available on stack overflow. Sadly none of them worked.
Here is the Code:
import discord
import asyncio
import datetime
from discord.ext import commands
bot = commands.Bot(command_prefix='!', case_insensitive=True)
#bot.event
async def on_ready():
print('bot is online')
return await bot.change_presence(activity=discord.Activity(type=2, name='bla'))
#bot.event
async def on_member_join(member):
embed = discord.Embed(colour=0x95efcc, description=f"Welcome! You are the {len(list(member.guild.members))} Member!"),
embed.set_thumbnail(url=f"{member.avatar_url}")
embed.set_author(name=f"{member.name}", url=f"{member.avatar_url}", icon_url=f"{member.avatar_url}")
embed.set_footer(text=f"{member.guild}", icon_url=f"{member.guild.icon_url}")
embed.timestemp = datetime.datetime.utcnow()
channel = bot.get_channel(id=012391238123)
await channel.send(embed=embed)
bot.run('Token')
The bot logs in but it won't execute on_member_join. Has anybody an idea what might be wrong? on_message works fine.
intents = discord.Intents.all()
client = discord.Client(intents=intents)
didn't help and in discord developer it's also checked (Server Members Intent).
The bot also has administrator privileges
Greetings Eduard
Solution in short:
imports
intents = discord.Intents(messages=True, guilds=True, members=True)
bot = commands.Bot(command_prefix='!', intents=intents, case_insensitive=True)
#bot.event
async def on_member_join(member):
embed = discord.Embed(colour=0x95efcc, description=f"Welcome to my discord server! You are the {len(list(member.guild.members))} member!")
channel = bot.get_channel(id=12931203123)
await channel.send(embed=embed)
bot.run('token')
Ah, so that's it.
Since you are using commands.Bot, the bot.get_channel is no longer a function (since it is no longer discord.Client). Try using member.guild.get_channel instead.
Documentation

How to work with on_member_join and on_member_remove in discord.py

I just started with discord.py and found out that on_member_join and on_member_remove don't work for me. Keep in mind that on_ready function works perfectly fine.
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix = "!")
#bot.event
async def on_ready():
print("""Bot ready""")
#bot.event
async def on_member_join(member):
channel = bot.get_channel(767370104814960640)
await channel.send(f"{member} has joined the server")
#bot.event
async def on_member_remove(member):
channel = bot.get_channel(766620766237753345)
await channel.send(f"{member} has left the server")
bot.run("my token")
So did I make a mistake with my code or something else went wrong?
discord.py 1.5.0 now supports discord API's Privileged Gateway Intents. In order to be able to exploit server data, you need to:
Enable Presence Intent and Server Members Intent in your discord application:
https://i.stack.imgur.com/h6IE4.png
Use discord.Intents at the beginning of your code:
intents = discord.Intents.all()
#If you use commands.Bot()
bot = commands.Bot(command_prefix="!", intents=intents)
#If you use discord.Client()
client = discord.Client(intents=intents)

Python Discord on_member_join

Excuse me for my bad english :-)
I have a problem that a Discord bot I work on does not send private message to members after they join. I tried several solutions suggested in other Stack Overflow posts, but it doesn't work.
import discord
client = discord.Client()
#client.event
async def on_member_join(member):
print(f'Someone joined')
await member.send("You joined")
client.run("XXX")
But the function is never executed.
If I use the exact same code in a command like ?join, as in the following example, it works!
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='?')
#client.command()
async def join(ctx):
member = ctx.message.author
print(f'Someone joined')
await member.send("You joined")
client.run("XXX")
So am I wrong thinking that on_member_join doesn't work anymore? What am I doing wrong?
Thanks for your time :-)
As of discord.py version 1.5+, Intents for bucket types of events must be stated by the bot prior to use. The event on_member_join needs the intent of discord.Intents.members to be set to True.
An easy way to do this is the following:
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='?', intents=intents)
discord.py version 1.5 states that if the intents are not specified, it allows all intents except for Intents.members and Intents.presences.
More information on Intents can be found here: Gateway Intents in discord.py

Discord Python Bot: How to move specific users mentioned by the author of the message

I am looking for a way to allow a user to move him or her self and another user to a different voice channel. I already got the command to work for the author of the message, but I am having trouble finding out a way to move another user in the same message. The idea is that the user would be able to type "n!negotiate [Other User]" and it would move the author and the other user to the Negotiation channel.
I would love some help with how I might be able to do this. The code is provided below excluding the tokens and ids.
Code:
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
Client = discord.Client() #Initialise Client
client = commands.Bot(command_prefix = "n!") #Initialise client bot and prefix
#client.event
async def on_ready():
print("Logged in as:")
print(client.user.name)
print("ID:")
print(client.user.id)
print("Ready to use!")
#client.event
async def on_message(check): #Bot verification command.
if check.author == client.user:
return
elif check.content.startswith("n!check"):
await client.send_message(check.channel, "Nations Bot is online and well!")
async def on_message(negotiation): #Negotiate command. Allows users to move themselves and other users to the Negotiation voice channel.
if negotiation.author == client.user:
return
elif negotiation.content.startswith("n!negotiate"):
author = negotiation.author
voice_channel = client.get_channel('CHANNELID')
await client.move_member(author, voice_channel)
client.run("TOKEN")
You should use discord.ext.commands. You're importing it, but not actually using any of the features.
from discord.ext import commands
import discord
bot = commands.Bot(command_prefix = "n!") #Initialize bot with prefix
#bot.command(pass_context=True)
async def check(ctx):
await bot.say("Nations Bot is online and well!")
#bot.command(pass_context=True)
async def negotiate(ctx, member: discord.Member):
voice_channel = bot.get_channel('channel_id')
author = ctx.message.author
await bot.move_member(author, voice_channel)
await bot.move_member(member, voice_channel)
bot.run('TOKEN')
Here we use a converter to accept a Member as input. Then we resolve the author of the message from the invocation context and move both Members to the voice channel.

Categories

Resources