Python continously receive message through websocket - python-3.x

I am trying to connect through websocket and keeping it alive to retrieve continously message from the server. I wrote the clientHelper and find the socketManager and ReconnectingWebsocket on the internet and I have not much idea on what going wrong with it as I do not receive anything thought the clientHelper.process_user_message function.
Can someone point me out the error please?
import websockets as ws
import asyncio
from client import Client
class ClientHelper(Client):
def __init__(self, api_key, api_secret):
super().__init__(api_key, api_secret)
self.loop = asyncio.get_event_loop()
def _request(self, method, uri, signed, force_params=False, **kwargs):
kwargs = self._get_request_kwargs(method, signed, force_params, **kwargs)
response = getattr(self.session, method)(uri, **kwargs)
return self._handle_response(response, method)
def _request(self, method, path, signed=False, version=API_VERSION, **kwargs):
uri = self._create_api_uri(path, signed, version)
return self._request(method, uri, signed, **kwargs)
def get_listen_key(self):
res = self._request('post', 'userDataStream', signed=True, data={})
return res['listenKey']
async def start_websockets(self):
self.sm = SocketManager(self, self.loop)
await self.sm.start_socket(self.process_user_message)
async def process_user_message(self, msg):
self.msg = msg
print(msg)
async def main(self)
await self.start_websockets()
while True:
await client.getInfo()
if 'data' in self.msg:
print(self.msg['data'])
def start(self):
self.loop.run_until_complete(self.main())
class SocketManager:
STREAM_URL = url
def __init__(self, client, loop, user_timeout=DEFAULT_USER_TIMEOUT):
self._client = client
self._loop = loop
self._conns = None
async def _start_user_socket(self, path, coro, prefix='ws/'):
if path in self._conns:
return False
self._conns[path] = ReconnectingWebsocket(self._loop, path, coro, prefix)
return path
async def start_user_socket(self, coro):
user_listen_key = await self._client.stream_get_listen_key() # manage to get the key from serveur
conn_key = await self._start_user_socket('user', user_listen_key, coro)
return conn_key
class ReconnectingWebsocket:
STREAM_URL = url
MAX_RECONNECTS = 5
MAX_RECONNECT_SECONDS = 60
MIN_RECONNECT_WAIT = 0.1
TIMEOUT = 10
def __init__(self, loop, path, coro, prefix='ws/'):
self._loop = loop
self._log = logging.getLogger(__name__)
self._path = path
self._coro = coro
self._prefix = prefix
self._reconnects = 0
self._conn = None
self._socket = None
self._connect()
def _connect(self):
self._conn = asyncio.ensure_future(self._run(), loop=self._loop)
async def _run(self):
keep_waiting = True
async with ws.connect(self.STREAM_URL) as socket:
self._socket = socket
self._reconnects = 0
try:
while keep_waiting:
try:
#evt = await self._coro(evt_obj)
evt = await asyncio.wait_for(self._socket.recv(), timeout=self.TIMEOUT)
except asyncio.TimeoutError:
#self._log.debug("no message in {} seconds".format(self.TIMEOUT))
print("no message in {} seconds".format(self.TIMEOUT))
await self.send_ping()
except asyncio.CancelledError:
#self._log.debug("cancelled error")
print("cancelled error")
await self.send_ping()
else:
try:
evt_obj = json.loads(evt)
except ValueError:
#self._log.debug('error parsing evt json:{}'.format(evt))
print('error parsing evt json:{}'.format(evt))
else:
await self._coro(evt_obj)
except ws.ConnectionClosed as e:
#self._log.debug('ws connection closed:{}'.format(e))
print('ws connection closed:{}'.format(e))
await self._reconnect()
except Exception as e:
#self._log.debug('ws exception:{}'.format(e))
print('ws exception:{}'.format(e))
await self._reconnect()
def _get_reconnect_wait(self, attempts: int) -> int:
expo = 2 ** attempts
return round(random() * min(self.MAX_RECONNECT_SECONDS, expo - 1) + 1)
async def _reconnect(self):
await self.cancel()
self._reconnects += 1
if self._reconnects < self.MAX_RECONNECTS:
reconnect_wait = self._get_reconnect_wait(self._reconnects)
await asyncio.sleep(reconnect_wait)
self._connect()
else:
self._log.error('Max reconnections {} reached:'.format(self.MAX_RECONNECTS))
async def send_ping(self):
if self._socket:
await self._socket.ping()
async def cancel(self):
self._conn.cancel()
self._socket = None

Related

NoneType' object has no attribute 'send error while mounting https session

I need mount session from specified ip address (192.168.100.40)
but getting next error:
response = self._session.send(request.prepare())
AttributeError: 'NoneType' object has no attribute 'send'
Problem in this two lines.if i removing mounting session parametrs
from
self.source_adapt = source.SourceAddressAdapter('192.168.100.40')
self._session = Session().mount('https://', self.source_adapt)
to self._session = Session() All is works but without binding of IP, that i need
What i doing wrong in my code ? :
import time
import urllib.parse
from typing import Optional, Dict, Any, List
from requests import Request, Session, Response
import hmac
from requests_toolbelt.adapters import source
class FtxClient:
_ENDPOINT = 'https://ftx.com/api/'
def __init__(self, api_key='my_key', api_secret='my_secret', subaccount_name=None) -> None:
self.source_adapt = source.SourceAddressAdapter('192.168.100.40')
self._session = Session().mount('https://', self.source_adapt)
self._api_key = api_key
self._api_secret = api_secret
self._subaccount_name = subaccount_name
def _post(self, path: str, params: Optional[Dict[str, Any]] = None) -> Any:
return self._request('POST', path, json=params)
def _request(self, method: str, path: str, **kwargs) -> Any:
request = Request(method, self._ENDPOINT + path, **kwargs )
self._sign_request(request)
response = self._session.send(request.prepare())
return self._process_response(response)
def _sign_request(self, request: Request) -> None:
ts = int(time.time() * 1000)
prepared = request.prepare()
signature_payload = f'{ts}{prepared.method}{prepared.path_url}'.encode()
if prepared.body:
signature_payload += prepared.body
signature = hmac.new(self._api_secret.encode(), signature_payload, 'sha256').hexdigest()
request.headers['FTX-KEY'] = self._api_key
request.headers['FTX-SIGN'] = signature
request.headers['FTX-TS'] = str(ts)
if self._subaccount_name:
request.headers['FTX-SUBACCOUNT'] = urllib.parse.quote(self._subaccount_name)
def _process_response(self, response: Response) -> Any:
try:
data = response.json()
except ValueError:
response.raise_for_status()
raise
else:
if not data['success']:
raise Exception(data['error'])
return data['result']
def add_ip(self) -> dict:
return self._post('direct_access_settings/add_ip', {
'name': "'test_15.29.137.131'",
'ip': "15.29.137.131"
})
def main():
client = FtxClient()
add_ip = client.add_ip()
print(add_ip)
if __name__ == '__main__':
main()

Python await is not finished but skipped

I am trying to implement an async database connection library to my FastAPI program, but it seems like python skips my await keyword.
My expected behaviour is that the login func will call get_user_info, which will print "before calling query" and then call _query and print "about to execute" and then print the result.
The actual outcome:
before calling query
user: None
INFO: 127.0.0.1:60548 - "POST /api/auth/login HTTP/1.1" 401 Unauthorized
2021-05-24 12:31:44.007 | INFO | authentication.routes:login:31 - 127.0.0.1 tried to log in with user x
my code:
route.py
#auth_app.post("/auth/login", response_model=Token, tags=["Authentication"])
async def login(request: Request, form_data: OAuth2PasswordRequestForm = Depends()):
credentials_exceptions = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect credentials.",
headers={"Authenticate": "Bearer"}
)
username = form_data.username
password = form_data.password
async with MysqlConnector() as conn:
user = await conn.get_user_info(username)
print("user:", user)
logger.info(f"{request.client.host} tried to log in with user {username}")
if not user:
raise credentials_exceptions
My MysqlConnector() class:
class MysqlConnector:
async def __aenter__(self):
await self._create_connection()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.connection.disconnect()
def __await__(self):
return self.__aenter__().__await__()
#staticmethod
def _create_conn_string():
return f"mysql://{MYSQL_SETTINGS['user']}:{MYSQL_SETTINGS['password']}#{MYSQL_SETTINGS['host']}:" \
f"{MYSQL_SETTINGS['port']}/{MYSQL_SETTINGS['database']}"
async def disconnect(self):
await self.connection.disconnect()
async def _create_connection(self):
MYSQL_SETTINGS['use_unicode'] = True
MYSQL_SETTINGS['charset'] = 'utf8'
self.connection = Database(self._create_conn_string())
await self.connection.connect()
async def _query(self, sql_query, dictionary=False, **kwargs):
print("about to execute")
await self.connection.execute(query=sql_query, values=kwargs)
self.res = await self.connection.fetch_all(query=sql_query)
print("result: ", self.res)
async def get_user_info(self, username: str) -> str:
sql_query = """
CALL `sp_get_user`(:username);
"""
try:
print("before calling query")
await self._query(sql_query, username=username)
result = self.res
print("result:")
print(result)
except IndexError:
return
user = User( # User is a pydantic model
user_id=result[0],
username=result[1],
first_name=result[2],
last_name=result[3],
role=result[4],
hashed_password=result[5],
email_addr=result[6],
phone=result[7],
desc=result[8],
last_login=datetime.strptime(result[9], '%Y-%m-%d %H:%M:%S.%f'),
active=result[10],
api_access=result[11]
)
print("user:", user)
return user
Thank you for any help!

Duplicate keys in a json file

When calling update_data(), it's meant to pass if there is the user.id in the .json file. All it does is add the same id to the .json file. So basically the .json file has 2 same keys as user.id.
I am assuming its something to do with the update_data() function but I can be wrong.
class LevelingSystem(commands.Cog):
""" Leveling system for discord """
def __init__(self, bot):
self.bot = bot
#commands.Cog.listener()
async def on_message(self, message):
async def update_data(levels, user):
if user not in levels:
levels[user] = {}
levels[user]["experience"] = 0
levels[user]["level"] = 1
print(" Registered {} to .json; set default;".format(user))
async def add_experience(levels, user):
experience_user = levels[user]["experience"] # gets the current user exp
exp = random.randint(1, 5) # random exp
experience_user += exp # adds the generated exp to the current exp
levels[user]["experience"] = experience_user #sets the user exp to that number
async def on_level_up(levels, user, message):
current_level = levels[user]["level"]
exp_next_level = 4 * (current_level + 1 ** 2)
exp = levels[user]["experience"]
if exp > exp_next_level:
old_level = levels[user]["level"]
new_level = old_level + 1
levels[user]["experience"] = 0
print(" {} advanced to lvl {}".format(user, new_level))
await message.channel.send(":partying_face: {} you have reached level {}".format(user.mention, new_level))
if message.author.bot:
return
else:
with open("X:\\Code\\Projects\\Python\\AlphaWolf\\cogs\\levels.json", 'r') as f:
levels = json.loads(f)
await update_data(levels, message.author.id)
await add_experience(levels, message.author.id)
await on_level_up(levels, message.author.id, message)
with open("X:\\Code\\Projects\\Python\\AlphaWolf\\cogs\\levels.json", 'w') as f:
json.dump(levels, f)
def setup(bot):
bot.add_cog(LevelingSystem(bot))
If you want to use the json library in a discord cog, here is a simple way to do it :
class LevelingSystem(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.base_xp = 200
self.factor = 2
#staticmethod
def get_data():
with open('members.json', 'r') as file:
return loads(file.read())
#staticmethod
def set_data(members):
with open('members.json', 'w') as file:
file.write(dumps(members, indent=2))
#commands.Cog.listener()
async def on_member_join(self, member):
members = self.get_data()
members.append({'name': member.name, 'id': member.id, 'level': 0,'xp': 0})
self.set_data(members)
#commands.Cog.listener()
async def on_member_remove(self, member):
members = self.get_data()
members.remove({'name': member.name, 'id': member.id, 'level': member.level,'xp': member.xp})
self.set_data(members)
#commands.Cog.listener()
async def on_message(self, message):
author = message.author.id
members = self.get_data()
for member in members:
if author == member['id']:
member['xp'] += randint(5, 10)
if member['xp'] > self.base_xp * (member['level']+1 * self.factor):
member['level'] += 1
await message.channel.send(f":partying_face: {message.author.mention} you have reached level {member['level'] !}")
self.set_data(members)
def setup(bot):
bot.add_cog(LevelingSystem(bot))
This is a good solution if you have few users tho. On a big server, you would have to create a database, you would have better performances.

How to reconnect to a websocket when connection fails in python

Hi I created async websocket client which I can receive and send messages asynchronously.
Here is the clint class that I use.
import websockets
import asyncio
from models import Heartbeat
from model_helper import ModelHelper
from json_helper import JSONHelper
from os.path import dirname, abspath
import logging
import time
waiting_time = 0.5
class WebSocketClient():
def __init__(self, websocket_queue, configs):
self.Heartbeat = Heartbeat().message
self.websocket_queue = websocket_queue
self.configs = configs
def get_connection_string(self):
server_url = self.configs.URL + ":" + str(self.configs.Port) + self.configs.Root
return server_url
async def connect(self):
try:
server_url = self.get_connection_string()
self.connection = await websockets.client.connect(server_url)
if self.connection.open:
print("Connection stablished. Client correcly connected")
# Send greeting
await self.connection.send(self.Heartbeat)
return self.connection
else:
print("Can not connect")
except ConnectionRefusedError as err:
print("Connection Error: {}".format(err))
async def send_message_to_socket(self, connection):
while True:
message = self.websocket_queue.get_send_queue()
try:
if message is not None:
message_ = ModelHelper.to_outgoing_request_model(message)
await connection.send(message_)
else:
await asyncio.sleep(waiting_time)
except websockets.exceptions.ConnectionClosed:
print('Connection with server closed')
self.connect()
async def receive_message_from_socket(self, connection):
while True:
try:
message = await connection.recv()
obj = JSONHelper.toObject(message)
print("Received object from websocket: {}".format(obj))
#If a websocket entry has SendMessage in its Action property
#Consider it as an sms content to be sent.
if(obj.Action == "SendMessage"):
self.websocket_queue.add_received_queue(obj)
except websockets.exceptions.ConnectionClosed:
print('Connection with server closed1')
async def send_heartbeat_to_socket(self, connection):
while True:
#print("Heartbeat loop\n")
try:
await connection.send(self.Heartbeat)
await asyncio.sleep(3)
except websockets.exceptions.ConnectionClosed:
print('Connection with server closed2')
And this is the code where I listen for websocket messages:
def listen_websocket_routine(sms_queue, websocket_queue):
while True:
time.sleep(waiting_time)
#Check Websocket queue for new messages
message = websocket_queue.get_received_queue()
# If Incoming websocket JSON has SendMessage string in its Action attribute transform it to request_model
if message is not None and send_sms.Action == "SendMessage":
# Transform it to outgoing_sms_model
reset = ModelHelper.to_outgoing_sms_model(message.Data)
# Add To send_queue of sms
sms_queue.add_send_queue(reset)
finally How I initiate them with asyncio and threading.
client = WebSocketClient(websocket_queue, configs)
loop = asyncio.get_event_loop()
connection = loop.run_until_complete(client.connect())
task1 = asyncio.ensure_future(client.receive_message_from_socket(connection))
task2 = asyncio.ensure_future(client.send_heartbeat_to_socket(connection))
task3 = asyncio.ensure_future(client.send_message_to_socket(connection))
listen_websocket_thread = threading.Thread(target=listen_websocket_routine, args=(sms_queue, websocket_queue))
listen_websocket_thread.start()
loop.run_forever()
So my question is, whenever connetion breaks, I need to re establish the connection. But I am not sure where should I do that. Should it be before everytime I try to send message or receive or should I do that in more general approach?
Since update 10.0 you could do it with an async iterator, like this(example from the official doc):
async for websocket in websockets.connect(...):
try:
...
except websockets.ConnectionClosed:
continue

Issue skipping song by requester

Hi I'm currently working on a music cog for my bot and I'm trying to figure out how to allow the song requester to skip the song without having to use the vote.
The music cog uses reactions to skip, stop, pause songs ect. The requester is the user who requested the song.
Here is what I'm trying to do:
if control == 'skip':
requester = self.requester
if requester:
vc.stop()
await channel.send('Requester skipped the song,')
else:
await channel.send(f':poop: **{user.name}** voted to skip **{source.title}**. **{react.count}/5** voted.', delete_after=8)
if react.count >= 5: # bot counts as 1 reaction.
vc.stop()
await channel.send(':track_next: **Skipping...**', delete_after=5)
I'm having an issue mainly with defining the song requester requester = self.requester
Here's snippet of the part of the code that defines requester:
class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source, *, data, requester):
super().__init__(source)
self.requester = requester
self.title = data.get('title')
if self.title is None:
self.title = "No title available"
self.web_url = data.get('webpage_url')
self.thumbnail = data.get('thumbnail')
if self.thumbnail is None:
self.thumbnail = "http://ppc.tools/wp-content/themes/ppctools/img/no-thumbnail.jpg"
self.duration = data.get('duration')
if self.duration is None:
self.duration = 0
self.uploader = data.get('uploader')
if self.uploader is None:
self.uploader = "Unkown"
# YTDL info dicts (data) have other useful information you might want
# https://github.com/rg3/youtube-dl/blob/master/README.md
def __getitem__(self, item: str):
"""Allows us to access attributes similar to a dict.
This is only useful when you are NOT downloading.
"""
return self.__getattribute__(item)
#classmethod
async def create_source(cls, ctx, search: str, *, loop, download=False):
loop = loop or asyncio.get_event_loop()
to_run = partial(ytdl.extract_info, url=search, download=download)
data = await loop.run_in_executor(None, to_run)
if 'entries' in data:
# take first item from a playlist
data = data['entries'][0]
await ctx.send(f':notes: **{data["title"]} added to the queue.**')
if download:
source = ytdl.prepare_filename(data)
else:
return {'webpage_url': data['webpage_url'], 'requester': ctx.author, 'title': data['title']}
return cls(discord.FFmpegPCMAudio(source), data=data, requester=ctx.author)
#classmethod
async def regather_stream(cls, data, *, loop):
"""Used for preparing a stream, instead of downloading.
Since Youtube Streaming links expire."""
loop = loop or asyncio.get_event_loop()
requester = data['requester']
to_run = partial(ytdl.extract_info, url=data['webpage_url'], download=False)
data = await loop.run_in_executor(None, to_run)
return cls(discord.FFmpegPCMAudio(data['url']), data=data, requester=requester)
class MusicPlayer:
"""A class which is assigned to each guild using the bot for Music.
This class implements a queue and loop, which allows for different guilds to listen to different playlists
simultaneously.
When the bot disconnects from the Voice it's instance will be destroyed.
"""
__slots__ = ('bot', '_guild', '_ctxs', '_channel', '_cog', 'queue', 'next', 'current', 'np', 'volume', 'buttons', 'music', 'music_controller', 'restmode')
def __init__(self, ctx):
self.buttons = {'⏯': 'rp',
'⏭': 'skip',
'➕': 'vol_up',
'➖': 'vol_down',
'🖼': 'thumbnail',
'⏹': 'stop',
'ℹ': 'queue',
'❔': 'tutorial'}
self.bot = ctx.bot
self._guild = ctx.guild
self._ctxs = ctx
self._channel = ctx.channel
self._cog = ctx.cog
self.queue = asyncio.Queue()
self.next = asyncio.Event()
self.np = None
self.volume = .5
self.current = None
self.music_controller = None
ctx.bot.loop.create_task(self.player_loop())
async def buttons_controller(self, guild, current, source, channel, context):
vc = guild.voice_client
vctwo = context.voice_client
for react in self.buttons:
await current.add_reaction(str(react))
def check(r, u):
if not current:
return False
elif str(r) not in self.buttons.keys():
return False
elif u.id == self.bot.user.id or r.message.id != current.id:
return False
elif u not in vc.channel.members:
return False
elif u.bot:
return False
return True
while current:
if vc is None:
return False
react, user = await self.bot.wait_for('reaction_add', check=check)
control = self.buttons.get(str(react))
if control == 'rp':
if vc.is_paused():
vc.resume()
else:
vc.pause()
await current.remove_reaction(react, user)
if control == 'skip':
requester = self.requester
if requester:
vc.stop()
await channel.send('Requester skipped the song,')
else:
await channel.send(f':poop: **{user.name}** voted to skip **{source.title}**. **{react.count}/5** voted.', delete_after=8)
if react.count >= 5: # bot counts as 1 reaction.
vc.stop()
await channel.send(':track_next: **Skipping...**', delete_after=5)
if control == 'stop':
mods = get(guild.roles, name="Mods")
for member in list(guild.members):
if mods in member.roles:
await context.invoke(self.bot.get_command("stop"))
return
else:
await channel.send(':raised_hand: **Only a mod can stop and clear the queue. Try skipping the song instead.**', delete_after=5)
await current.remove_reaction(react, user)
if control == 'vol_up':
player = self._cog.get_player(context)
vctwo.source.volume += 2.5
await current.remove_reaction(react, user)
if control == 'vol_down':
player = self._cog.get_player(context)
vctwo.source.volume -= 2.5
await current.remove_reaction(react, user)
if control == 'thumbnail':
await channel.send(embed=discord.Embed(color=0x17FD6E).set_image(url=source.thumbnail).set_footer(text=f"Requested By: {source.requester} | Video Thumbnail: {source.title}", icon_url=source.requester.avatar_url), delete_after=10)
await current.remove_reaction(react, user)
if control == 'tutorial':
await channel.send(embed=discord.Embed(color=0x17FD6E).add_field(name="How to use the music controller?", value="⏯ - Pause\n⏭ - Skip\n➕ - Increase Volume\n➖ - Increase Volume\n🖼 - Get Thumbnail\n⏹ - Stop & Leave\nℹ - Queue\n❔ - Display help for music controls"), delete_after=10)
await current.remove_reaction(react, user)
if control == 'queue':
await self._cog.queue_info(context)
await current.remove_reaction(react, user)
If anyone could help me an example of what I'm doing wrong would be awesome! Thanks.
You should be checking requester against the user that reacted to the message.
if control == 'skip':
if self.requester == user:
...
else:
...
With your current code, I would expect the song to always be skipped, as any User or Member object it truthy. You should double-check what is actually being assigned to self.requester.
#Patrick Here is how I'm doing it with your answer, however when the skip '⏭': 'skip', reaction is used it doesn't skip the requester song and causes all the reactions to not function.
Here is the full code:
import discord
from discord.ext import commands
import asyncio
import itertools, datetime
import sys
import traceback
from async_timeout import timeout
from functools import partial
from youtube_dl import YoutubeDL
from discord.ext.commands.cooldowns import BucketType
from cogs.utils.opus_loader import load_opus_lib
from .utils import checks
from discord.utils import get
import asyncio
if not discord.opus.is_loaded():
load_opus_lib()
ytdlopts = {
'format': 'bestaudio/best',
'outtmpl': 'downloads/%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0'
}
ffmpegopts = {
'before_options': '-nostdin -preset ultrafast',
'options': '-vn -threads 1'
}
ytdl = YoutubeDL(ytdlopts)
class VoiceConnectionError(commands.CommandError):
"""Custom Exception class for connection errors."""
class InvalidVoiceChannel(VoiceConnectionError):
"""Exception for cases of invalid Voice Channels."""
class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source, *, data, requester):
super().__init__(source)
self.requester = requester
self.title = data.get('title')
if self.title is None:
self.title = "No title available"
self.web_url = data.get('webpage_url')
self.thumbnail = data.get('thumbnail')
if self.thumbnail is None:
self.thumbnail = "http://ppc.tools/wp-content/themes/ppctools/img/no-thumbnail.jpg"
self.duration = data.get('duration')
if self.duration is None:
self.duration = 0
self.uploader = data.get('uploader')
if self.uploader is None:
self.uploader = "Unkown"
# YTDL info dicts (data) have other useful information you might want
# https://github.com/rg3/youtube-dl/blob/master/README.md
def __getitem__(self, item: str):
"""Allows us to access attributes similar to a dict.
This is only useful when you are NOT downloading.
"""
return self.__getattribute__(item)
#classmethod
async def create_source(cls, ctx, search: str, *, loop, download=False):
loop = loop or asyncio.get_event_loop()
to_run = partial(ytdl.extract_info, url=search, download=download)
data = await loop.run_in_executor(None, to_run)
if 'entries' in data:
# take first item from a playlist
data = data['entries'][0]
await ctx.send(f':notes: **{data["title"]} added to the queue.**')
if download:
source = ytdl.prepare_filename(data)
else:
return {'webpage_url': data['webpage_url'], 'requester': ctx.author, 'title': data['title']}
return cls(discord.FFmpegPCMAudio(source), data=data, requester=ctx.author)
#classmethod
async def regather_stream(cls, data, *, loop):
"""Used for preparing a stream, instead of downloading.
Since Youtube Streaming links expire."""
loop = loop or asyncio.get_event_loop()
requester = data['requester']
to_run = partial(ytdl.extract_info, url=data['webpage_url'], download=False)
data = await loop.run_in_executor(None, to_run)
return cls(discord.FFmpegPCMAudio(data['url']), data=data, requester=requester)
class MusicPlayer:
"""A class which is assigned to each guild using the bot for Music.
This class implements a queue and loop, which allows for different guilds to listen to different playlists
simultaneously.
When the bot disconnects from the Voice it's instance will be destroyed.
"""
__slots__ = ('bot', '_guild', '_ctxs', '_channel', '_cog', 'queue', 'next', 'current', 'np', 'volume', 'buttons', 'music', 'music_controller', 'restmode')
def __init__(self, ctx):
self.buttons = {'⏯': 'rp',
'⏭': 'skip',
'➕': 'vol_up',
'➖': 'vol_down',
'🖼': 'thumbnail',
'⏹': 'stop',
'ℹ': 'queue',
'❔': 'tutorial'}
self.bot = ctx.bot
self._guild = ctx.guild
self._ctxs = ctx
self._channel = ctx.channel
self._cog = ctx.cog
self.queue = asyncio.Queue()
self.next = asyncio.Event()
self.np = None
self.volume = .5
self.current = None
self.music_controller = None
ctx.bot.loop.create_task(self.player_loop())
async def buttons_controller(self, guild, current, source, channel, context):
vc = guild.voice_client
vctwo = context.voice_client
for react in self.buttons:
await current.add_reaction(str(react))
def check(r, u):
if not current:
return False
elif str(r) not in self.buttons.keys():
return False
elif u.id == self.bot.user.id or r.message.id != current.id:
return False
elif u not in vc.channel.members:
return False
elif u.bot:
return False
return True
while current:
if vc is None:
return False
react, user = await self.bot.wait_for('reaction_add', check=check)
control = self.buttons.get(str(react))
if control == 'rp':
if vc.is_paused():
vc.resume()
else:
vc.pause()
await current.remove_reaction(react, user)
if control == 'skip':
if self.requester == user:
await channel.send('Requester skipped.')
vc.stop()
else:
await channel.send(f':poop: **{user.name}** voted to skip **{source.title}**. **{react.count}/5** voted.', delete_after=8)
if react.count >= 5: # bot counts as 1 reaction.
vc.stop()
await channel.send(':track_next: **Skipping...**', delete_after=5)
if control == 'stop':
mods = get(guild.roles, name="Mods")
for member in list(guild.members):
if mods in member.roles:
await context.invoke(self.bot.get_command("stop"))
return
else:
await channel.send(':raised_hand: **Only a mod can stop and clear the queue. Try skipping the song instead.**', delete_after=5)
await current.remove_reaction(react, user)
if control == 'vol_up':
player = self._cog.get_player(context)
vctwo.source.volume += 2.5
await current.remove_reaction(react, user)
if control == 'vol_down':
player = self._cog.get_player(context)
vctwo.source.volume -= 2.5
await current.remove_reaction(react, user)
if control == 'thumbnail':
await channel.send(embed=discord.Embed(color=0x17FD6E).set_image(url=source.thumbnail).set_footer(text=f"Requested By: {source.requester} | Video Thumbnail: {source.title}", icon_url=source.requester.avatar_url), delete_after=10)
await current.remove_reaction(react, user)
if control == 'tutorial':
await channel.send(embed=discord.Embed(color=0x17FD6E).add_field(name="How to use the music controller?", value="⏯ - Pause\n⏭ - Skip\n➕ - Increase Volume\n➖ - Increase Volume\n🖼 - Get Thumbnail\n⏹ - Stop & Leave\nℹ - Queue\n❔ - Display help for music controls"), delete_after=10)
await current.remove_reaction(react, user)
if control == 'queue':
await self._cog.queue_info(context)
await current.remove_reaction(react, user)
async def player_loop(self):
"""Our main player loop."""
await self.bot.wait_until_ready()
while not self.bot.is_closed():
self.next.clear()
try:
async with timeout(3500):
source = await self.queue.get()
except asyncio.TimeoutError:
return self.destroy(self._guild)
if not isinstance(source, YTDLSource):
# Source was probably a stream (not downloaded)
# So we should regather to prevent stream expiration
try:
source = await YTDLSource.regather_stream(source, loop=self.bot.loop)
except Exception as e:
await self._channel.send(f'An error occured!.\n'
f'```css\n[{e}]\n```')
continue
source.volume = self.volume
self.current = source
try:
self._guild.voice_client.play(source, after=lambda _: self.bot.loop.call_soon_threadsafe(self.next.set))
except Exception:
continue
embednps = discord.Embed(color=0x17FD6E)
embednps.add_field(name="Currently Playing:", value=f"```fix\n{source.title}```", inline=False)
embednps.add_field(name="Requested By:", value=f"**{source.requester}**", inline=True)
embednps.add_field(name="Source:", value=f"**[URL]({source.web_url})**", inline=True)
embednps.add_field(name="Uploader:", value=f"**{source.uploader}**", inline=True)
embednps.add_field(name="Duration:", value=f"**{datetime.timedelta(seconds=source.duration)}**", inline=True)
embednps.set_thumbnail(url=source.thumbnail)
self.np = await self._channel.send(embed=embednps)
self.music_controller = self.bot.loop.create_task(self.buttons_controller(self._guild, self.np, source, self._channel, self._ctxs))
await self.next.wait()
# Make sure the FFmpeg process is cleaned up.
source.cleanup()
self.current = None
try:
# We are no longer playing this song...
await self.np.delete()
self.music_controller.cancel()
except Exception:
pass
def destroy(self, guild):
"""Disconnect and cleanup the player."""
return self.bot.loop.create_task(self._cog.cleanup(guild))
class Music:
"""Music cog for UKGBot."""
__slots__ = ('bot', 'players', 'musictwo', 'music_controller')
def __init__(self, bot):
self.bot = bot
self.players = {}
async def cleanup(self, guild):
try:
await guild.voice_client.disconnect()
except AttributeError:
pass
try:
del self.players[guild.id]
except KeyError:
pass
async def __local_check(self, ctx):
"""A local check which applies to all commands in this cog."""
if not ctx.guild:
raise commands.NoPrivateMessage
return True
async def cleanup(self, guild):
try:
await guild.voice_client.disconnect()
except AttributeError:
pass
try:
del self.players[guild.id]
except KeyError:
pass
async def __error(self, ctx, error):
"""A local error handler for all errors arising from commands in this cog."""
if isinstance(error, commands.NoPrivateMessage):
try:
return await ctx.send(':notes: Command cannot be used in DM.')
except discord.HTTPException:
pass
elif isinstance(error, InvalidVoiceChannel):
await ctx.send("Connect to a voice channel first!")
print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
def get_player(self, ctx):
"""Retrieve the guild player, or generate one."""
try:
player = self.players[ctx.guild.id]
except KeyError:
player = MusicPlayer(ctx)
self.players[ctx.guild.id] = player
return player
#commands.command(name='stop', aliases=[ 'l', 'disconnect'])
#checks.is_channel_mod()
async def disconnect_(self, ctx):
"""Stops and leaves the voice channel."""
try:
channel = ctx.author.voice.channel
except AttributeError:
await ctx.send(":notes: You are not connected to a voice channel.", delete_after=20)
if not ctx.guild.voice_client:
return await ctx.send(':notes: I\'m not connected to the voice channel.', delete_after=20)
await ctx.guild.voice_client.disconnect()
await ctx.send(':wave: Stopped and left the channel.', delete_after=20)
#commands.command(name='reconnect', aliases=['rc'])
async def reconnect_(self, ctx):
try:
channel = ctx.author.voice.channel
except AttributeError:
return await ctx.send(":notes: You are not connected to a voice channel.", delete_after=20)
if ctx.guild.voice_client:
await ctx.guild.voice_client.disconnect()
await channel.connect()
#commands.command(name='connect', aliases=['join','summon'])
async def connect_(self, ctx, *, channel: discord.VoiceChannel=None):
"""connectss to a voice channel."""
try:
channel = ctx.author.voice.channel
except AttributeError:
return await ctx.send(":notes: You are not connected to a voice channel.", delete_after=20)
await channel.connect()
#commands.command(name='skip', aliases=['sk'])
#checks.is_channel_mod()
async def skip_(self, ctx, *, channel: discord.VoiceChannel=None):
"""Skips a song (Mods)."""
try:
channel = ctx.author.voice.channel
except AttributeError:
return await ctx.send(":notes: You are not connected to a voice channel.", delete_after=20)
ctx.guild.voice_client.stop()
await ctx.send(':track_next: **Skipping...**', delete_after=5)
#commands.command(name='play', aliases=['sing', 'p'])
async def play_(self, ctx, *, search: str):
"""searches for and plays a song."""
await ctx.trigger_typing()
vc = ctx.voice_client
try:
channel = ctx.author.voice.channel
if not vc:
await ctx.invoke(self.connect_)
except AttributeError:
return await ctx.send(":notes: You are not connected to a voice channel.", delete_after=20)
player = self.get_player(ctx)
# If download is False, source will be a dict which will be used later to regather the stream.
# If download is True, source will be a discord.FFmpegPCMAudio with a VolumeTransformer.
source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop, download=False)
await player.queue.put(source)
#commands.command(name='playing', aliases=['np', 'current', 'currentsong', 'now_playing'])
async def now_playing_(self, ctx):
"""Shows the current song playing."""
vc = ctx.voice_client
if not vc or not vc.is_connected():
return await ctx.send("I'm not connected to a voice channel..", delete_after=20)
elif ctx.author not in ctx.guild.voice_client.channel.members:
return await ctx.send("You need to be in the voice channel first!", delete_after=20)
player = self.get_player(ctx)
if not player.current:
return await ctx.send("There's nothing currently playing.", delete_after=20)
try:
# Remove our previous now_playing message.
await player.np.delete()
except discord.HTTPException:
pass
embednp = discord.Embed(color=0x17FD6E)
embednp.add_field(name="Currently Playing:", value=f"```fix\n{vc.source.title}```", inline=False)
embednp.add_field(name="Requested By:", value=f"**{vc.source.requester}**", inline=True)
embednp.add_field(name="Source:", value=f"**[URL]({vc.source.web_url})**", inline=True)
embednp.add_field(name="Uploader:", value=f"**{vc.source.uploader}**", inline=True)
embednp.add_field(name="Duration:", value=f"**{datetime.timedelta(seconds=vc.source.duration)}**", inline=True)
embednp.set_thumbnail(url=f"{vc.source.thumbnail}")
player.np = await ctx.send(embed=embednp)
self.music_controller = self.bot.loop.create_task(MusicPlayer(ctx).buttons_controller(ctx.guild, player.np, vc.source, ctx.channel, ctx))
async def queue_info(self, ctx):
player = self.get_player(ctx)
if player.queue.empty():
return await ctx.send('**:notes: No songs currently queued.**', delete_after=5)
upcoming = list(itertools.islice(player.queue._queue, 0, 5))
fmt = '\n'.join(f'**`{_["title"]}`**' for _ in upcoming)
embed = discord.Embed(title=f'{len(upcoming)} songs queued.', description=fmt, color=0x17FD6E)
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(Music(bot))
Look at your signature, async def buttons_controller(self, guild, current, source, channel, context): What you are looking for is source as source = song "the song you have requested".
Therefore you would need to add source in front of requester as requester = the member and after this you need to define user as we are looking the specific requester on reaction add.
So you have this:
if control == 'skip':
if source.requester == user:
vc.stop()

Resources