nextcord slash command profile command - nextcord

from nextcord.ext import commands
import nextcord
from typing import Optional
from nextcord import Interaction,Member,Embed,Color,Intents,SlashOption
async def SlashProfile(interaction: nextcord.Interaction, user: Member=None):
inline = True
embed = Embed(title=user.name+'#'+user.discriminator, colour = 0xFF0404)
userData = {
'Mention' : user.mention,
'Nick' : user.nick,
'Join date': user.joined_at.strftime("%b %d, %Y %T"),
'Account Creation Date': user.created_at.strftime("%b %d, %Y %T")
}
for [fieldName, fieldVal] in userData.items():
embed.add_field(name=fieldName+':', value=fieldVal, inline=inline)
embed.set_footer(text=f"id: {user.id}")
embed.set_thumbnail(user.display_avatar)
await interaction.response.send_message(embed=embed)
What should be done to make the user argument optional? I have tried making user optional using the Optional class from the typing Module and then using Slash option's required argument to be False but it gives out typeerror as im not sure of the datatype used for user pings.

Related

Discord Slash Command options not working

I am trying to make a slash command in discord.
import discord
import datetime
import pickle
import os
from discord.ext import commands
from dislash import *
bot = commands.Bot(command_prefix="-")
inter_client = InteractionClient(bot, test_guilds=[345328981039382528])
#bot.event
async def on_ready():
print("Nick ist online!")
#inter_client.slash_command(
name="kick", # Defaults to the function name
description="kick a user",
guild_ids=[345328981039382528],
options=[
create_option(
name="user",
description="Choose a user",
option_type=6,
required=True
)
]
)
async def kick(inter, user:str):
pass
bot.run("-")
If i am trying to run it it says:
Traceback (most recent call last):
line 20, in <module>
create_option(
NameError: name 'create_option' is not defined
So someone said i should add the following line:
from discord_slash.utils.manage_commands import create_option
But this does not help. After adding this it says:
line 7, in <module>
from discord_slash.utils.manage_commands import create_option
ModulNotFoundError: No module named 'discord_slash'
However if i go to cmd and do:
pip install discord-py-slash-command
It says its already installed.
Does anyone know what i am doing wrong? Thanks for helping
options=[
Option("user","Choose a user", OptionType.USER)
]
Try changing your options in the slash command to as follows.

Streamlit Unhashable TypeError when i use st.cache

when i use the st.cache decorator to cash hugging-face transformer model i get
Unhashable TypeError
this is the code
from transformers import pipeline
import streamlit as st
from io import StringIO
#st.cache(hash_funcs={StringIO: StringIO.getvalue})
def model() :
return pipeline("sentiment-analysis", model='akhooli/xlm-r-large-arabic-sent')
after searching in issues section in streamlit repo
i found that hashing argument is not required , just need to pass this argument
allow_output_mutation = True
This worked for me:
from transformers import pipeline
import tokenizers
import streamlit as st
import copy
#st.cache(hash_funcs={tokenizers.Tokenizer: lambda _: None, tokenizers.AddedToken: lambda _: None})
def get_model() :
return pipeline("sentiment-analysis", model='akhooli/xlm-r-large-arabic-sent')
input = st.text_input('Text')
bt = st.button("Get Sentiment Analysis")
if bt and input:
model = copy.deepcopy(get_model())
st.write(model(input))
Note 1:
calling the pipeline with input model(input) changes the model and we shouldn't change a cached value so we need to copy the model and run it on the copy.
Note 2:
First run will load the model using the get_model function next run will use the chace.
Note 3:
You can read more about Advanced caching in stremlit in thier documentation.
Output examples:

How to correct TypeError with choices() missing 1 required positional argument: 'population'

I want list of entries to display when calling the random page function but I keep getting this error choices() missing 1 required positional argument: 'population'.
I had this problem due a typo recently.
Aparently you are using the recommended 'secrets' PNG and not 'random' pseudoPNG. I had the following code:
#!/usr/bin/python3
"""
Will get 10 random letters...
from the lowercase abcdefghijklmnopqrstuvwxyz
"""
import string
import secrets
response = secrets.SystemRandom.choices(string.ascii_lowercase, k=10)
print(response)
But secrets.SystemRandom is a class, so I just changed it to secrets.SystemRandom() and the issue was fixed.
Fixed code:
#!/usr/bin/python3
"""
Will get 10 random letters...
from the lowercase abcdefghijklmnopqrstuvwxyz
"""
import string
import secrets
response = secrets.SystemRandom().choices(string.ascii_lowercase, k=10)
print(response)

Python error: one of the arguments is required

I'm trying to run a code from github that uses Python to classify images but I'm getting an error.
here is the code:
import argparse as ap
import cv2
import imutils
import numpy as np
import os
from sklearn.svm import LinearSVC
from sklearn.externals import joblib
from scipy.cluster.vq import *
# Get the path of the testing set
parser = ap.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-t", "--testingSet", help="Path to testing Set")
group.add_argument("-i", "--image", help="Path to image")
parser.add_argument('-v',"--visualize", action='store_true')
args = vars(parser.parse_args())
# Get the path of the testing image(s) and store them in a list
image_paths = []
if args["testingSet"]:
test_path = args["testingSet"]
try:
testing_names = os.listdir(test_path)
except OSError:
print "No such directory {}\nCheck if the file exists".format(test_path)
exit()
for testing_name in testing_names:
dir = os.path.join(test_path, testing_name)
class_path = imutils.imlist(dir)
image_paths+=class_path
else:
image_paths = [args["image"]]
and this is the error message I'm getting
usage: getClass.py [-h]
(- C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset/test TESTINGSET | - C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset/test/test_1.jpg IMAGE)
[- C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset]
getClass.py: error: one of the arguments - C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset/test/--testingSet - C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset/test/test_1.jpg/--image is required
can you please help me with this? where and how should I write the file path?
This is an error your own program is issuing. The message is not about the file path but about the number of arguments. This line
group = parser.add_mutually_exclusive_group(required=True)
says that only one of your command-line arguments (-t, -i) is permitted. But it appears from the error message that you are supplying both --testingSet and --image on your command line.
Since you only have 3 arguments, I have to wonder if you really need argument groups at all.
To get your command line to work, drop the mutually-exclusive group and add the arguments to the parser directly.
parser.add_argument("-t", "--testingSet", help="Path to testing Set")
parser.add_argument("-i", "--image", help="Path to image")
parser.add_argument('-v',"--visualize", action='store_true')

why pxssh.before behaves different when used with py.test.?

from pexpect import pxssh
import getpass
import time
import sys
s=pxssh.pxssh()
class Testinstall:
def setup_class(cls):
cls.s=pxssh.pxssh()
cls.s.login('10.10.62.253', 'User','PW',auto_prompt_reset=False)
def teardown_class(cls):
cls.s.logout()
def test_cleanup(cls):
cls.s.sendline('cat test.py')
cls.s.prompt(timeout=10)
cls.s.sendline('cat profiles.conf')
cls.s.prompt(timeout=10)
print('s.before')
print (cls.s.before)
print('s.after')
print(cls.s.after)
In above code print(cls.s.before) prints, output of both cat commands.
As per expectation it should only print output of the 2nd cat command i.e cat profiles.conf.
When tried in python session in shell it shows output of only second cat command ( as per expectation)
If you use auto_prompt_reset=False for pxssh.login() then you cannot use pxssh.prompt(). According to the doc:
pxssh uses a unique prompt in the prompt() method. If the original prompt is not reset then this will disable the prompt() method unless you manually set the PROMPT attribute.
So for your code, both prompt() would time out and .before would have all output and .after would be pexpect.exceptions.TIMEOUT.
The doc also says that
Calling prompt() will erase the contents of the before attribute even if no prompt is ever matched.
but this is NOT true based on my testing:
>>> from pexpect import pxssh
>>> ssh = pxssh.pxssh()
>>> ssh.login('127.0.0.1', 'root', 'passwd')
True
>>> ssh.PROMPT = 'not-the-real-prompt'
>>> ssh.sendline('hello')
6
>>> ssh.prompt(timeout=1)
False
>>> ssh.before
'hello\r\n-bash: hello: command not found\r\n[PEXPECT]# '
>>> ssh.after
<class 'pexpect.exceptions.TIMEOUT'>
>>> ssh.sendline('world')
6
>>> ssh.prompt(timeout=1)
False
>>> ssh.before
'hello\r\n-bash: hello: command not found\r\n[PEXPECT]# world\r\n-bash: world: command not found\r\n[PEXPECT]# '
>>> ssh.after
<class 'pexpect.exceptions.TIMEOUT'>
>>>
From the result you can see .before is not erased for the 2nd prompt(). Instead it's appended with the new output.
You can use ssh.sync_original_prompt() instead of ssh.prompt().

Resources