socket disconnect and connect after some time python - socket.io

I am working on a project, using WSGI server. My connect agents and users disconnected and again connected after some time with new sid (session IDs). Which is creating a problem. I need same sid throughout the user interaction on the web. And are eventlet used for?
New to sockets need help on this issue.
here is my code:
import socketio
import os
from dotenv import load_dotenv
import jwt
from Controllers.DatabaseController import DBController
DBHandler = DBController()
load_dotenv()
private_key = os.getenv('PRIVATE_KEY')
# headers = {'Authorization': private_key}4
sio = socketio.Server(ping_interval=25,ping_timeout=55)
app = socketio.WSGIApp(sio, static_files={
'/': './public/'
})
agents = {}
users = {}
total_agents = 0
def add_agents(sid, First_Name, Last_Name):
global total_agents
if (total_agents >= 0):
total_agents += 1
agents[sid] = {
'Type': 'Agent',
'First_Name': First_Name,
'Last_Name': Last_Name,
'Data': {}
}
return agents
def add_users(sid):
global total_users
if (total_users >= 0):
total_users += 1
users[total_users] = {
sid: {
'Data': ''
}
}
return agents
#sio.event
def connect(sid, environ):
global agents
token = environ.get('HTTP_X_USERNAME')
print(token)
if not token:
print(sid, 'connected')
return True
try:
user_session_data = jwt.decode(token, private_key, algorithms='HS256')
# if user_session_data is False:
# with sio.session(sid) as session:
# session['username'] = token
# sio.emit('user_joined', 1)
# print(sid, 'connected')
# users_list = add_users(sid)
# print(users_list)
#
# print(user_session_data)
result, colnames = DBHandler.GetAgentData(user_session_data['user'])
if result is not False:
First_Name = result[0][0]
Last_Name = result[0][1]
Username = result[0][2]
with sio.session(sid) as session:
session['username'] = token
#sio.emit(Username, 1)
print(sid, 'connected')
agents_list = add_agents(sid, First_Name, Last_Name)
sio.enter_room(sid, 'agents')
print(agents_list)
except Exception as e:
print(e)
print("wrong token ")
return False
#sio.event
def disconnect(sid):
print(sid, 'disconnected')
sio.leave_room(sid, 'agents')
del agents[sid]
#sio.event
def request_call(sid):
sio.emit('call_request', {'sid': sid}, room='agents')
#sio.event
def accept_call(sid):
sio.emit('call_accepted', {'sid': sid}, to=sid)

Related

Discord has no attribute named 'StoreChannel'

I am trying to make a discord bot that returns the most popular videos in the KR region regarding a topic which actually is the message of the user.
So far i coded import discord
import googleapiclient.discovery
from discord.ext import commands
import typing
from discord_ui import UI
cmd = commands.Bot(command_prefix='.')
client = discord.Client()
token =
api_service_name = "youtube"
api_version = "v3"
DEVELOPER_KEY = 'googleapikeyhere'
youtube = googleapiclient.discovery.build(
api_service_name, api_version, developerKey=DEVELOPER_KEY)
#cmd.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.reply(f"You are on cooldown for {round(error.retry_after, 2)} seconds!")
# cmd.command()
# commands.cooldown(1, 4, commands.BucketType.user)
async def info(ctx, *args):
output2 = ''
for word in args:
output2 += str(word)
output2 += ' '
print(output2)
request3 = youtube.videos().list(
part="snippet, {}, statistics".format(output2),
chart="mostPopular",
regionCode="KR"
)
response3 = request3.execute()
print(response3)
channame = response3['items'][0]['snippet']['title']
chanid = response3['etag']
numberViews = response3['Items'][0]['statistics']['viewCount']
numberLikes = response3['Items'][0]['statistics']['likeCount']
embed2 = discord.Embed(title=f"{channame}", url=f"https://www.youtube.com/watch?v={chanid}",
numberviews=f"{numberViews}", numberlikes= f"{numberLikes}", color=0xFF5733)
response3 = request3.execute()
await ctx.send(embed=embed2)
cmd.run('findvideos')
but it results in the error discord has no attribute 'StoreData' why is that ?

Change discord.py embed field position

Is it possible to change the position of an embed field in discord.py?
Here is my more detailed problem:
I have an embed, but I have to make it modular, which means that with a command we can either add a field or delete one. The delete command works and the add command works, but now I need to be able to change the position of the field to be the same as the position of the role (because each field corresponds to a role).
How can I do that?
We can't edit embed field's position, but we can try to add every fields in the good ordor so we don't have to edit the field's position !
Here are my codes (working):
import asyncio
import discord
from discord.ext import commands
from datetime import datetime
intents = discord.Intents.all()
bot = commands.Bot(command_prefix = "!1789", help_command = None, intents=intents)
async def get_hour():
now = ""
now = datetime.now()
hour = now.strftime("%H:%M")
return hour
async def role_members_mention(role: discord.Role, emoji):
role_str = ""
if len(role.members):
for member in role.members:
role_str += f"**|** {emoji} **➜** {member.mention}\n"
role_str[:-1]
return role_str
async def soon(role, emoji, max):
soon = f"**|** {emoji} **➜ Soon**\n" * (int(max[role.name].replace("/", "")) - len(role.members))
soon[:-1]
return soon
async def get_all_roles():
guild = bot.get_guild(966749409314504774)
global ceo_aceo_roles_dict
ceo_aceo_roles_dict = {}
ceo = discord.utils.get(guild.roles, id = 966749523949023262)
aceo = discord.utils.get(guild.roles, id = 992137775883243530)
global all_roles_dict
all_roles_dict = {}
all_roles_dict[ceo.position] = ceo
all_roles_dict[aceo.position] = aceo
ceo_aceo_roles_dict[ceo.position] = ceo
ceo_aceo_roles_dict[aceo.position] = aceo
async def update_effective():
ceo_aceo = ""
embed = discord.Embed(title = "**E͟͟͟F͟͟͟F͟͟͟E͟͟͟C͟͟͟T͟͟͟I͟͟͟F͟͟͟ S͟͟͟T͟͟͟A͟͟͟F͟͟͟F͟͟͟**. <:3446blurplecertifiedmoderator:1001403463214825542>", description = "", color = 0x000000)
max = {}
total = {}
effectif_staff_emojis = ["<:adcrown:1001400557073866762>", "<:bluesettings:1001472768161894532>", "<:diplome:1001472522811883621>", "<:5961blurpleemployee:1001403806828994570>"]
roles_staff_emojis = ["<:5961blurpleemployee:1001403806828994570>", "<:Dev:1001412860091580487>", "<:direction:1001476149051924591>", "<:bluevoicechannel:1001473637091659836", "<:direction:1001476149051924591>", "<:spideyn7:996331019735158864>", "<:logo_twitch:1005196891010629702>"]
all_roles = sorted(all_roles_dict)
ceo_aceo_roles = sorted(ceo_aceo_roles_dict)
all_roles.reverse()
ceo_aceo_roles.reverse()
x = -1
for role in all_roles:
x += 1
all_roles[x] = all_roles_dict[role]
x = -1
for role in ceo_aceo_roles:
x += 1
ceo_aceo_roles[x] = ceo_aceo_roles_dict[role]
for role in all_roles:
number = 0
for car in role.name:
if car == "‎":
number += 1
max[role.name] = "/" + str(number)
if len(role.members) >= int(max[role.name].replace("/", "")):
total[role.name] = f"🔒 **{str(len(role.members))} {max[role.name]}**"
else:
total[role.name] = f"🔓 **{str(len(role.members))} {max[role.name]}**"
message = await (await get_effective_staff_channel()).fetch_message(1059250505689337998)
for role in ceo_aceo_roles:
ceo_aceo += f"{role.mention} {total[role.name]}\n{await role_members_mention(role, effectif_staff_emojis[0])}{await soon(role, effectif_staff_emojis[0], max)}\n\n"
embed.add_field(name = "**C.E.O & A.C.E.O** <:adcrown:1001400557073866762>", value = ceo_aceo, inline = False)
embed.set_thumbnail(url = "https://media.discordapp.net/attachments/1001404772496187392/1059246720669733014/Picsart_22-10-19_21-20-35-971.jpg?width=1326&height=529")
embed.set_image(url = "https://media.discordapp.net/attachments/1001404772496187392/1059246720875241542/Picsart_22-10-13_21-14-41-363.jpg?width=618&height=618")
await message.edit(embed = embed)
async def delete_messages(ctx, number_of_message_to_delete = 1, time_to_wait = 0):
await asyncio.sleep(time_to_wait)
await ctx.channel.purge(limit=number_of_message_to_delete)
#bot.event
async def on_ready():
print(f"[{await get_hour()}] Ready !\n Username: {bot.user.name}\n----------------------------------------------------")
await get_all_roles()
await update_effective()
while True:
await asyncio.sleep(600)
await update_effective()
#bot.command()
#commands.has_permissions(administrator = True)
async def addeffectifstaff(ctx, role: discord.Role, number = 1):
await delete_messages(ctx)
role = discord.utils.get(ctx.guild.roles, id = role.id)
if role in all_roles_dict.values():
await ctx.send("Désolé mais ce rôle est déjà dans l'effectif.")
else:
ceo_aceo_roles_dict[role.position] = role
all_roles_dict[role.position] = role
await update_effective()
await ctx.send(f"Bien ! Le rôle {role.name} a été ajouté à l'effectif !")
await delete_messages(ctx, 1, 3)
print(f'[{await get_hour()}] {ctx.author.name} used the command "addeffectifstaff" to make me add the role "{role.name}" to the effective message.')
#bot.command()
#commands.has_permissions(administrator = True)
async def deleffectif(ctx, role: discord.Role):
await delete_messages(ctx)
role = discord.utils.get(ctx.guild.roles, id = role.id)
if not role in all_roles_dict.values():
await ctx.send("Désolé mais ce rôle n'est déjà pas dans l'effectif.")
else:
ceo_aceo_roles_dict.pop(role.position)
all_roles_dict.pop(role.position)
await update_effective()
await ctx.send(f"Bien ! Le rôle {role.name} a été supprimé de l'effectif !")
await delete_messages(ctx, 1, 3)
print(f'[{await get_hour()}] {ctx.author.name} used the command "deleffectif" to make me remove the role "{role.name}" to the effective message.')
bot.run(token)

Error Implementing free dictionary Api in discord.py

I am trying to implement this api but the code says error every single time.
My code so far:
#client.command()
async def mean(ctx,word):
response = requests.get(f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}")
if response.status_code == 404:
await ctx.send("No such word")
return
else:
wordx = response.json()
the_dictionary = wordx[0]
meanings = the_dictionary['meanings']
definitions = meanings[0]
definition = definitions['definitions']
meaningg = definition[0]
meaning = meaningg['definition']
example = meaningg.get('example',['None'])
synonymslist = meaningg.get("synonyms",['None'])
if isinstance(synonymslist,str):
synonymslist = [synonymslist]
pass
synonyms = ','.join(synonymslist)
deffinal= discord.Embed(title=f"`{word.upper()}`")
deffinal.add_field(name = "Definition", value=f"{meaning}")
deffinal.add_field(name = 'Example', value = f"{example}")
deffinal.add_field(name = "Synonyms", value = f"{synonyms}")
await ctx.channel.send(embed = deffinal)
Here is the error message:
Your error does not come from the API call to the dictionary api, but rather from your call to the discord api.
The error message says discord.errors.HTTPException: [...] In embed.fields.2.value: This field is required.
So the error comes from an empty field in your embed! The field has index 2 so it is actually the third field (Synonyms) which is causing the problem.
You can simply check if a string is empty, before even adding the field. And if it is empty, just don't add it.
deffinal= discord.Embed(title=f"`{word.upper()}`")
if meaning:
deffinal.add_field(name = "Definition", value=f"{meaning}")
if example:
deffinal.add_field(name = 'Example', value = f"{example}")
if synonyms:
deffinal.add_field(name = "Synonyms", value = f"{synonyms}")
#client.command()
async def mean(ctx,word):
response = requests.get(f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}")
if response.status_code == 404:
await ctx.send("No such word")
return
else:
wordx = response.json()
the_dictionary = wordx[0]
meanings = the_dictionary['meanings']
definitions = meanings[0]
definition = definitions['definitions']
meaningg = definition[0]
meaning = meaningg['definition']
example = meaningg.get('example',['None'])
synonymslist = meaningg.get("synonyms",['None'])
if isinstance(synonymslist,str):
synonymslist = [synonymslist]
pass
synonyms = ','.join(synonymslist)
deffinal= discord.Embed(title=f"`{word.upper()}`")
if meaning:
deffinal.add_field(name = "Definition", value=f"{meaning}")
if example:
deffinal.add_field(name = 'Example', value = f"{example}")
if synonyms:
deffinal.add_field(name = "Synonyms", value = f"{synonyms}")
await ctx.channel.send(embed = deffinal)
Adding to itzFlubby answer, using requests will be blocking read more which means if you block for too long then your bot will freeze since it has not stopped the function’s execution at that point to do other things.
Here is the final code, also I changed the format a bit to make it easier to read.
# import aiohttp
#bot.command()
async def mean(ctx, word):
async with aiohttp.ClientSession() as session:
async with session.get(f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}") as r:
if r.status == 200:
info = await r.json()
else:
return await ctx.reply("No such word")
the_dictionary = info[0]['meanings'][0]['definitions'][0]
definition = the_dictionary.get('definition')
example = the_dictionary.get('example')
synonymslist = the_dictionary.get("synonyms")
# if only one synonym is avaliable
if isinstance(synonymslist, str):
synonymslist = [synonymslist]
synonyms = '\n'.join(synonymslist)
deffinal = discord.Embed(title=f"`{word.upper()}`")
if definition:
deffinal.add_field(name="Definition", value=f"```{definition}```")
if example:
deffinal.add_field(name='Example', value=f"```{example}```")
if synonyms:
deffinal.add_field(name="Synonyms", value=f"```{synonyms}```")
await ctx.reply(embed=deffinal)

aws sign up InvalidLambdaResponseException

i'm getting this error while signing up users :
An error occurred (InvalidLambdaResponseException) when calling the SignUp operation: Unrecognizable lambda output.
my code :
from __future__ import print_function
import json
import boto3
import botocore.exceptions
import hmac
import hashlib
import base64
import json
import uuid
client = None
USER_POOL_ID = 'us-east-2_ssqaX****';
CLIENT_ID = '40kq19dp3tgaost148115****';
CLIENT_SECRET = '1rbns01jnv2ckiu1so8ntqjt8l6r****lgq2a4hni642s*****';
ERROR = 0
SUCCESS = 1
USER_EXISTS = 2
def get_secret_hash(username):
msg = username + CLIENT_ID
dig = hmac.new(str(CLIENT_SECRET).encode('utf-8'),
msg = str(msg).encode('utf-8'), digestmod=hashlib.sha256).digest()
d2 = base64.b64encode(dig).decode()
print("here" + d2)
return d2
def lambda_handler(event, context):
global client
if client == None:
client = boto3.client('cognito-idp')
body = event
username = body['username']
password = body['password']
resp = client.sign_up(
ClientId=CLIENT_ID,
SecretHash=get_secret_hash(username),
Username=username,
Password=password
)
return {"resp": resp}
An error occurred (InvalidLambdaResponseException) when calling the SignUp operation: Unrecognizable lambda output: InvalidLambdaResponseException

Openshift 3.X with Websockets

I'm trying to host a websocket-application op Openshift 3, but I have running into some issues.
Code at the backend:
templatePath = os.path.join(os.path.dirname(__file__), "templates")
staticPath = os.path.join(os.path.dirname(__file__), "static")
settings = {
"template_path": templatePath,
"static_path": staticPath,
"debug" : True
}
application = web.Application([
(r'/ws', WSHandler),
(r'/', MainHandler, {"staticFilesPath":staticPath}),
(r"/(.*)", tornado.web.StaticFileHandler, {'path': staticPath}),
],**settings)
class WSHandler(tornado.websocket.WebSocketHandler):
def initialize(self, messageHandler):
print 'Initializing MessageHandler'
self.messageHandler = messageHandler
def check_origin(self,origin):
return True
def open(self):
print 'Connection received'
def on_message(self, message):
message = simplejson.loads(message)
print 'received message of type "' + message['type'] + '"'
outputMessage = {'type': 'Hello', 'data': 'World'}
self.sendMessage(outputMessage)
def on_close(self):
print 'Connection closed'
class MainHandler(tornado.web.RequestHandler):
def initialize(self, staticFilesPath):
self.staticFilesPath = staticFilesPath
def get(self):
print 'New connection'
webClientHtml = os.path.join(self.staticFilesPath,'index.html')
loader = tornado.template.Loader(".")
self.write(loader.load(webClientHtml).generate())
At the frontend:
var hostname = window.document.location.hostname;
var host = "ws://" + hostname + ":8000/ws";
var ws = new WebSocket(host);
This leads to ERR_CONNECTION_TIMED_OUT. I know the port 8000 had to be specified in Openshift 2. The documentation I could find about websocket-ports op Openshift 3 seems to suggest this is no longer necessary, but I can't figure out what to use. I have tried 80 and not specifying a port, but neither works.
Does anybody know what I'm doing wrong?

Resources