get the number of users in a voice channel with my discord bot in python - discord

I'm looking for a way to get the number of users in a voice channel and to get their username to use it in one of my discord bot command, I found that I can use ctx.guild.member to get the members of users in the server, but not in a specific channel, is there a method to do that ?
I tried this
from discord.ext import commands
bot = commands.Bot(intents=discord.Intents.all(),command_prefix = "/")
#bot.command()
async def teamup(ctx):
channel = ctx.author.VoiceChannel
Or this
bot = commands.Bot(intents=discord.Intents.all(),command_prefix = "/")
#bot.command()
async def teamup(ctx):
channel = ctx.message.author.voice.channel
None of them works, the first tells me that member objects has no attribute VoiceChannel
and the second one tells me that ctx.message.author.voice is a NoneType object and has no attribute channel

You're very close.
#bot.command()
async def teamup(ctx):
channel = ctx.message.author.voice.channel
ctx has an author property; this returns the user/member object for the individual that invoked the command. The user/member has a voice property that returns the VoiceState object of the user. This has a channel property which will return the voice channel that the user is in. Importantly, this will be None if the user isn't in a voice channel. So, putting it together:
#bot.command()
async def teamup(ctx):
voice = ctx.author.voice
if not voice.channel:
await ctx.send("You are not currently in a voice channel")
return
channel = voice.channel
# do what you want with the channel here
await ctx.send(f"You're in {channel.name}!")

Related

Ask for channel ID through a command in Discord.py?

I'm new to Discord py and trying to make my bot get the channel ID using a command like >sending [numbers] but it's not actually working. The error I get is
TypeError: get_channel() missing 1 required positional argument: 'id'
This is how I'm trying to make it:
from discord import Client
from discord import channel
from discord.ext import commands
id_chnl = ''
#bot.command()
async def sending(ctx, *, chnl):
global id_chnl
id_chnl = cnhl
global channel
channel = Client.get_channel(str(id_chnl))
await ctx.send("Saving your ID")
I don't know what your trying to but getting channel object is easy using command by converters.
All you have to do is,
#bot.command()
async def sending(ctx, channel: discord.TextChannel):
channel_id = channel.id
Note: There are different types of channels - text, voice, stage, category and store. Each of the uses different converters and you can find them in the docs.
If you want to get any one of the channel regardless of the type,
channel: typing.Union[discord.TextChannel, discord.VoiceChannel, discord.StoreChannel, discord.StageChannel, discord.CategoryChannel]```
been a bit, but try:
channel = Client.get_channel(id=str(id_chnl))
The easist way to get the channel the bot is in is:
#bot.command()
async def sending(ctx):
channel_id = ctx.channel.id
The easist way to get the channel by using #:
#bot.command()
async def sending(ctx, channel: discord.TextChannel):
channel_id = channel.id
To fetch the channel:
#bot.command()
async def sending(ctx, channel: discord.TextChannel):
channel_id = await bot.fetch_channel(channel.id)
Alternative way might be using name:
#bot.command()
async def sending(ctx, channel: discord.TextChannel):
channel = discord.utils.get(ctx.guild.channels, name=channel) #or instead of name it would be id

discord.py sending message to channel name instead of ID

I am a beginner to this programming stuff, and I have a quick question. I am trying to make a logs channel for multiple servers, and I want to be able to look for a channel that has the word “logs” in it, so can you help me?
Code:
#client.event
async def on_command_completion(ctx):
channel = client.get_channel('829067962316750898')
embed = discord.Embed(colour=discord.Color.green(),
title="Command Executed")
embed.add_field(name="Command:", value=f"`,{ctx.command}`")
embed.add_field(name="User:", value=f"{ctx.author.mention}", inline=False)
embed.add_field(name="Channel:",
value=f"{ctx.channel} **( <#{ctx.channel.id}> )**")
await channel.send(embed=embed)
You need to get the channel. I suggest using discord.utils.get.
Also, try using {ctx.channel.mention} to mention the channel instead.
#client.event
async def on_command_completion(ctx):
channel = discord.utils.get(ctx.guild.text_channels, name='logs')
if channel is None:
return # If there is no logs channel, do nothing (or what you want to do)
embed = discord.Embed(colour=discord.Color.green(),
title="Command Executed")
embed.add_field(name="Command:", value=f"`,{ctx.command}`")
embed.add_field(name="User:", value=f"{ctx.author.mention}", inline=False)
embed.add_field(name="Channel:",
value=f"{channel.name} **( {channel.mention} )**")
await channel.send(embed=embed)
See the discord.TextChannel docs and discord.utils.get()

discord.py how to make the bot ban someone if they have a certain word in their name

I was wondering how I could ban someone if they had someone in their name. For example, I have people who join with the n word in their name and I wanted to know how I could ban them for having that in their name.
You can use the discord.Member object given by on_member_join to get the user's name, and filter names that way.
import discord
intents = discord.Intents.default()
intents.members = True #So you can use on_member_join event
client = discord.Client(intents=intents)
banlist = []
#client.event
async def on_member_join(member):
if any(banned in member.name for banned in banlist):
await member.ban()
return

Is there a way to make a discord bot that sends a user a message the mentioned number of times?

I've been trying to make a discord bot with discord.py. I know how to make the bot send a message to the specified user, but I was wondering, is there a way to send the message a given number of times? If so, how can I do it?
As an example, if the user types !dm #discorduser hello 5, the bot will send "hello" to the specified user 5 times.
So far, my code is:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='.')
#client.event
async def on_ready():
print('Bot is ready.')
#client.command()
async def spam(ctx, member: discord.Member, *, content):
channel = await member.create_dm()
await channel.send(content)
client.run('bot token')
Here's my answer for the question, from my understanding you're trying to Direct Message a user x amount of times, and x can be changed depending on what the user wants.
#client.command()
# the arguments are: member, the amount of times you want to DM, and what you want to DM them.
async def spam(ctx, member : discord.Member, amount=1, content=None):
# this loop will keep doing the script below the amount of 'amount' times.
for i in range(amount):
channel = await member.create_dm()
await channel.send(content)

Discord.py welcome bot on_member_join event not getting callded

I've been interested in working with discord bots lately, and from what I'm seeing this code should work but it is not...
I'm simply just playing around with the API because it's fun so I'm pretty new with this. I just want the bot to welcome someone when they join.
import discord
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
channel = client.guilds[0].get_channel(CHANNEL ID)
await channel.send("Bot online")
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
#client.event
async def on_member_join(member):
print(f'{member.name} has joined the server')
channel = client.guilds[0].get_channel(CHANNEL ID)
print(channel)
await channel.send(f'{member.name} has joined the server')
#client.event
async def on_member_remove(member):
print(f'{member.name} has left the server')
channel = client.guilds[0].get_channel(CHANNEL ID)
print(channel)
await channel.send(f'{member.name} has left the server')
client.run('TOKEN HERE')
instead of member.name use member and if that dosnt work add this where you have your variables intents = discord.Intents(messages = True, guilds = True, reactions = True, members = True, presences = True)
client = commands.Bot(command_prefix = '*', intents = intents)
FOR discord.py >= 1.5
1.5 adds support for Gateway Intents, by default your bot doesn't have access to guild members like it did in previous versions. If your bot is in less than 100 servers then you can enable these intents without verification. You should see these settings at the bottom of your Bot page on the Discord Developer Portal. If you enable both, then you need to change your Client (or commands.Bot) instantiation as such:
intents = discord.Intents.all()
client = discord.Client(intents=intents)
When I test this, the event is firing, but I'll bet your issue lies in the line:
channel = client.guilds[0].get_channel(CHANNEL ID)
It will be far more reliable to just use use client.get_channel to ensure you are actually grabbing the intended channel, all channel IDs on discord are unique so you do not need to use a guild object. Also CHANNEL ID will not be a valid variable, but I am guessing you just redacted it.
You forgot the brackets for the decorators.
#client.event
should be
#client.event()
EDIT: Not it, apparently. Will update this answer when OP replies with more information.

Resources