Get the user voice channel id - python

I have this following function:
async def play_youtube_url(youtube_url):
channel = client.get_channel('VOICE_CHANNEL_ID')
if youtube_url.startswith('https://www.youtube.com/watch?v='):
voice = await client.join_voice_channel(channel)
player = await voice.create_ytdl_player(youtube_url)
player.start()
else:
return 'URL_ERROR'
My question is, how can I get the voice channel id of the user that typed the command. I know how to get the server id, but i can't find how to get the voice channel id in the documentation. Thanks!

Use command extension and context:
import discord
from discord.ext import commands
...
client = commands.Bot(command_prefix="!")
#client.command(pass_context=True)
async def play_youtube_url(self, ctx, youtube_url):
channel = ctx.message.author.voice.voice_channel
# http://discordpy.readthedocs.io/en/latest/api.html#discord.Member.voice
# http://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceState.voice_channel
if youtube_url.startswith('https://www.youtube.com/watch?v='):
voice = await client.join_voice_channel(channel)
player = await voice.create_ytdl_player(youtube_url)
player.start()
else:
return 'URL_ERROR'
...
client.run("token")

Related

How to I make a my discord bot join a voice channel *in a category*?

I'd like to write a bot with the ability to join; This is my code
import json
import discord
from discord.ext import commands
JSON_FILE = r"C:\JSON PATH"
bot = commands.Bot(command_prefix = "~")
with open(JSON_FILE, "r") as json_file:
TOKEN = json.load(json_file)["token"]
GUILD = json.load(json_file)["guild"]
bot = commands.Bot(command_prefix = "~")
#bot.event
async def on_ready():
print(f"{bot.user.name} launched and has arrived for further use")
#bot.command(name = "join")
async def join(ctx, voice_channel: commands.VoiceChannelConverter):
await voice_channel.connect()
await ctx.send(f"I have joined: {voice_channel}")
#bot.command(name = "leave")
async def leave(ctx):
server = ctx.message.server
voice_client = bot.voice_client_int(server)
await voice_client.disconnect()
bot.run(TOKEN)
It can join usual channels but it cannot join channels in categories. Any advice on how to do that?
Thank you in advance
The problem is probably, that you are using an outdated version of discord.py since you are using server, which is deprecated since v1.0, and not guild. If you update it, it will probably work, because it worked for me too when I tried it.
To code it to automatically join the voice channel of the user executing the command, just use ctx.author.voice.channel:
#bot.command(name = "join")
async def join(ctx, voice_channel: commands.VoiceChannelConverter):
if not ctx.author.voice is None:
await ctx.author.voice.channel.connect()
await ctx.send(f"I have joined your voice channel.")
else:
await ctx.send("You are not in a voice channel!")
References:
discord.Member.voice
Server is deprecated

How to set channel ID for multiple discord servers in python

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')

Discord.py Bot Not Playing music

Hi guys, for some reason my bot can actually join, but is not able to play audio.
Actually I am totally new to that and I was trying to get it to work like 2 hours and managed just to set up join but not play (or leave) command.
import os
import random
from dotenv import load_dotenv
import youtube_dl
import discord
from discord.ext import commands
from discord.ext import commands
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
players={}
bot = commands.Bot(command_prefix='!')
#bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
#bot.command(name="Ja_som_to_nebol.")
async def sranda(ctx):
sranda_quotes = ["Not gonna lie, kinda sus",
("Not gonna lie, kinda sus"), ]
response = random.choice(sranda_quotes)
await ctx.send(response)
##bot.event
#async def on_command_error(ctx, error):
# if isinstance(error, commands.errors.CheckFailure):
# await ctx.send('You do not have the correct role for this command.')
#bot.command(name="join")
async def join(ctx):
channel = ctx.author.voice.channel
await channel.connect()
#bot.command(name="leave")
async def leave(ctx):
channel = ctx.author.voice.channel
await channel.disconnect()
#bot.command(name="play")
async def play(ctx, url):
guild = ctx.author.voice.channel
voice_client = discord.utils.find(lambda c: c.guild.id == server.id, client.voice_client)
player = await voice_client.create_ytdl_player(url)
players=[server.id] = player
player.start()
bot.run(TOKEN)
instead of playing like this use my code which I uses you must have FFmpeg installed.
#commands.command(name='play', aliases=['p'])
async def _play(self, ctx: commands.Context, *, search: str):
if not ctx.voice_state.voice:
await ctx.invoke(self._join)
async with ctx.typing():
try:
source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop)
except YTDLError as e:
await ctx.send('An error occurred while processing this request: {}'.format(str(e)))
else:
song = Song(source)
await ctx.voice_state.songs.put(song)
await ctx.send('Enqueued {}'.format(str(source)))
I am using some Cogs here you can edit to normal code by yourself.

Problem Getting an input from user in Discord.py

Hey
How I am supposed to input a string from a user in Discord.py. I am getting errors while trying to get input from user. It would be great if someone can help me :)
import discord
from discord import embeds
from discord.ext.commands import Bot
from discord.ext import commands
import time
client = discord.Client()
embed = discord.Embed()
bot = commands.Bot(command_prefix='.')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('.gdrive'):
first_embed = discord.Embed(title="Unlimited Google Drive Storage", color=0x2bff00)
new_embed = discord.Embed(title='Made by zSupremeSniper0 & toxicXvoid', color=0x2bff00)
new_embed2 = discord.Embed(title='Please Enter your gmail', color=0x2bff00)
# send a first message with an embed
msg = await message.channel.send(embed=first_embed)
# edit the embed of the message
time.sleep(5)
await msg.edit(embed=new_embed)
time.sleep(5)
await msg.edit(embed=new_embed2)
You can use Client.wait_for to wait for a user input:
# edit the embed of the message
time.sleep(5)
await msg.edit(embed=new_embed)
time.sleep(5)
await msg.edit(embed=new_embed2)
def check(m):
return m.channel == message.channel
msg = await client.wait_for('message', check=check)
await message.channel.send("OK")

Discord Fetch Random message from a Channel [Python]

The bot should fetch a random message from a diffrent channel and send it to the channel where the command was made.
Example: Im in #chat and it should fetch a random message from #memes and post it in #chat where I made the command.
Heres the code I made which doesn't really work.
#client.command()
async def meme(ctx, message_id, channel_id):
guild = ctx.guild
channel = guild.get_channel(int(672740818645417984))
message = guild.fetch_message(random.choice(int(message_id)))
message = await channel.fetch_message(int(message_id))
await channel.send(message)
Currently as Error it can't get the message_id
This works.
#client.command()
async def meme(ctx):
channel = client.get_channel("channel id")
allmes = []
async for message in channel.history(limit=200):
allmes.append(message)
randoms = random.choice(allmes).content
await ctx.send(randoms)

Categories