Check if an item is in the bag using json (economy system bot discord.py)
This is the code for my "bag" or inventory command
@client.command()
async def bag(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
try:
bag = users[str(user.id)]["bag"]
except:
bag = []
em = discord.Embed(title = "Bag")
for item in bag:
name = item["item"]
amount = item["amount"]
em.add_field(name = name, value = amount)
await ctx.send(embed = em)
So i want to check if there is a specific item in the bag. Suppose the item name is "common", how would i do that? Ive tried numerous for item in bag
and stuff like that but none work!
See also questions close to this topic
-
Server error while posting JSON data to server in C#
I have a problem that I can't seem to wrap my head around. I am trying to call my web api using httpClient but getting a 500 Internal server error. Searched several posts but couldn't find the exact issue. I know it is JSON formatting but not sure what's missing. Below is my client function:
[Microsoft.SqlServer.Server.SqlProcedure(Name = "myCallStoredProc")] public static void myCallStoredProc(SqlString BaseApiUrl, SqlString ApiName, SqlString ApiKey, SqlString InputJson, out int RtnCd, out string RtnMsg) { try { ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; var httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(BaseApiUrl.ToString()); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Add("API_KEY", ApiKey.ToString()); //var content = new StringContent(null, Encoding.UTF8, "application/json"); var content = new StringContent(InputJson.ToString(), Encoding.UTF8, "application/json"); var response = httpClient.PostAsync(ApiName.ToString(), content).Result; RtnCd = response.IsSuccessStatusCode == true ? 0 : -1; RtnMsg = RtnCd == -1 ? response.Content.ReadAsStringAsync().Result : ""; return; } catch (Exception ex) { RtnCd = -1; RtnMsg = ex.ToString(); } }
This is my InputJson:
"{\"PnsHandle\":\"<value>\",\"PnsType\":\"<value>\",\"Template\":\"{\"data\":{\"title\":\"$(title)\",\"message\":\"$(message)\"}}\",\"TagList\":\"<value>\",\"InstallationId\":\"<value>\",\"AzureHubServiceName\":\"<value>\",\"AzureHubName\":\"<value>\",\"AzureHubListenAccessKeyName\":\"<value>\",\"AzureHubListenAccessKeyValue\":\"<value>\"}"
When I execute myCallStoredProc with required input and above InputJson value, I get following error:
After parsing a value an unexpected character was encountered: d. Path 'Template', line 1, position 110.
My web api looks like below:
[HttpPost] public async Task<HttpResponseMessage> myAPI(HttpRequestMessage request) { try { string input = await request.Content.ReadAsStringAsync(); JObject inputValues = JObject.Parse(input); // Do Something with inputValues return Request.CreateResponse(HttpStatusCode.OK, result); } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex); } }
I tried to format the input json using online json formatters and after removing the escape '' the json turned out fine.
I searched multiple posts with same issues here and here but they are talking about how to send the post data like using httpwebrequest or using httpClient which I am already doing.
Any comments on what I might be doing wrong here? It seems to me the json formatting issue but not sure.
-
Python seems to only read one item per top-level arrays
I have a JSON file that I read in Python. The JSON (see below) contains two top-level items, both are arrays, containing complex structure, including other arrays at lower levels. For some reason, Python seems to only read one item from both top level arrays.
This is the JSON:
{ "deliverables": [ { "name": "<uvCode>gadget1", "objects": [ { "name": "handler-plate" }, { "name": "Cone" } ] }, { "name": "<uvCode>gadget2", "objects": [ { "name": "handler-plate" }, { "name": "Cone" } ] } ], "uvCombinations": [ { "name": "st01", "uvMapping": [ { "objectNameContains": "handler-plate", "uvLayer": "UVMap1" }, { "objectNameContains": "Cone", "uvLayer": "UVMap1" } ] }, { "name": "st02", "uvMapping": [ { "objectNameContains": "handler-plate", "uvLayer": "UVMap3" }, { "objectNameContains": "Cone", "uvLayer": "UVMap2" } ] } ] }
This is my code to read and dump the JSON file:
with open("file.json") as configFile: configuration = json.load(configFile) logging.debug("CONFIG: %s", json.dumps(configuration, indent=4))
And this is the output:
CONFIG: { "deliverables": [ { "name": "<uvCode>gadget1", "objects": [ { "name": "handler-plate" }, { "name": "Cone" } ] } ], "uvCombinations": [ { "name": "st02", "uvMapping": [ { "objectNameContains": "handler-plate", "uvLayer": "UVMap3" }, { "objectNameContains": "Cone", "uvLayer": "UVMap2" } ] } ] }
The second item of array
deliverables
(with name<uvCode>gadget2
) and the first item of arrayuvCombination
(the one with namest01
) is somehow missing.I'm not a Python expert, but I think this should work like charm, and it's strange that the missing items are not even of the same index. It get even more interesting if you observe that arrays called
objects
anduvMapping
are read properly.What am I doing wrong?, the poor guy asks
-
The JSON value could not be converted to System.Int32 python POST
I have an issue with the POST method in python.
My code :
url = "https://blablabla.com" data = { "data1": "blalba", "data2": "12" } resp = requests.post(url, json=data) print(resp.text)
My output is :
{"result":false,"data":null,"error":{"httpStatusCode":0,"errorMessages":null,"isError":false},"validationErrors":[{"field":"$.sicno","error":["The JSON value could not be converted to System.Int32. Path: $.sicno | LineNumber: 0 | BytePositionInLine: 18."]}],"isError":true}
how can I handle it? Thank you.
-
Python2.7 works but Python3.x throws error
def calculate(self): normals = [] for f in self.sides: sideN= A(0.0, 0.0, 0.0) for i in range(0, len(f)): p1 = self.ver[f[(i - 1) % len(f)]] p2 = self.ver[f[i]] p3 = self.ver[f[(i + 1) % len(f)]] v1 = p2 - p1 v2 = p2 - p3 v33 = v2.cross(v1) v33 = v33.normalize() sideN += v33 sideN = sideN.normalize() normals.append(sideN) return normals
this runs OK on python 2.7 but when I run in on python 3.8 it throws
p1 = self.ver[f[(i - 1) % len(f)]] TypeError: list indices must be integers or slices, not float
when I edit that part;
p1 = self.ver[f[(i - 1) % len(f)]] p2 = self.ver[f[i]] p3 = self.ver[f[(i + 1) % len(f)]]
to that
p1 = self.ver[int(f[(i - 1) % len(f)])] p2 = self.ver[int(f[i])] p3 = self.ver[int(f[(i + 1) % len(f)])]
then it throws;
p3 = self.ver[int(f[(i + 1) % len(f)])] IndexError: list index out of range
I tried 2to3 but nothing is changed. What is the problem here?
-
How can I find full path for a file?
Let's say I have this path
D:\something\something1\from_here_I_now\stuff\stuff2
.So, I know that
\from_here_I_now\stuff\stuff2
is a permanent path, but the beginning is different, like I know thatD:\something\something1\
may be different for someone else. How can I find theD:\something\something1\
knowing only\from_here_I_now\stuff\stuff2
? -
Why is this PyGTK menu empty?
I am working on a PyGTK application with a
Gtk.Toolbar
. One of the items in taht toolbar is aGtk.MenuToolButton
. However, clicking on the arrow once the program runs results in an empty menu (a tiny white sliver). Here is the code that sets up the menu:self.compileMenu = Gtk.Menu() self.defaultCompileOption = Gtk.MenuItem(label = "Compile with defaults") self.configCompileOption = Gtk.MenuItem(label = "Change compile options...") self.compileWithFiles = Gtk.MenuItem(label = "Bundle files...") self.compileMenu.append(self.defaultCompileOption) self.compileMenu.append(self.configCompileOption) self.compileMenu.append(self.compileWithFiles) self.compileButton = Gtk.MenuToolButton(icon_name = "x-package-repository", label = "Compile...", menu = self.compileMenu)
There is also a call to
self.toolbar.add
at the bottom, to add theMenuToolButton
to the toolbar. -
What is the simplest way to kick/ban members using Discord.py?
I am trying to code a Discord bot, and I would like to add commands so that people with kick/ban permissions can use the kick/ban commands. I found a lot of sites about this, but they all seem a bit too complex. It is also difficult to integrate a lot of the solutions I found into my code.
Below is what the code currently looks like:
from discord.ext import commands import os from dotenv import load_dotenv import logging # Enables logging logger = logging.getLogger('discord') logger.setLevel(logging.DEBUG) handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w') handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')) logger.addHandler(handler) # Assigns the Discord client to a variable called client client = commands.Bot(command_prefix='$') # Loads .env load_dotenv() # Prints a message stating that the bot is loggen in @client.event async def on_ready(): print('Logged in as {0.user}'.format(client)) # Prints the help message when a user says $help @client.event async def on_message(message): if message.content.startswith('$help'): await message.channel.send('''**Hydra Help** *This message contains a list of commands and what they do.* __help__: Prints this message.''') # Starts the bot client.run(os.getenv('TOKEN'))
I already have a decent setup, I just can't figure out how to implement kick/ban commands into the code. Could someone help?
-
How to make to be able to run only one command or event at a time in discord.py bot
I'm trying to solve a problem, I have many commands and events in my discord bot (minigames) and I want users to be able to use only one command at a time so if there is one minigame already running, other commands or events can't be used. So I created
on_command
variable and at the beginning of every command and event the variable changes to 1 and at the end of every command and event the variable changes back to 0. So if someone tries to use some command or event and the variable is 1, the bot just sends him that he can't use that command now. But for some reason it doesn't work and I get the next error:discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local variable 'on_command' referenced before assignment
My code:
on_command = 0 @bot.command() @commands.cooldown(1, 180.0, commands.BucketType.guild) async def question(msg): if msg.channel.id != channel: return if on_command == 1: await msg.send("Another command or event is running") return on_command = 1 .... .... .... on_command = 0
-
How to create a discord Magic 8ball bot that sends embeds (discord.py)
So I am trying to create a Magic 8ball bot. And I got the code to work. But, I want to send the response in Embed, and I am having trouble doing that. Also I created what i want it to look like using a sim. Can anyone help me? Here is what i want it to look like.
-
Modifying timestamp in discord.py
I am making a giveaway command for myself, but I can't figure out how to display the end time of the giveaway as an embed timestamp, could anyone help? I read through the embed docs but that did not really help, maybe I am stupid, but I cant figure it out.
@bot.command() async def giveaway(ctx, timer=None): if not timer: await ctx.send(f"only use #s for seconds. #m for minutes. #h for hours. #d for days. ") return if '.' not in timer: time_in_sec = 0 if (timer[-1] == 'h') and (timer.count('h') == 1): time_in_sec = int(timer[:-1]) * 3600 type__ = 'hour' elif (timer[-1] == 'm') and (timer.count('m') == 1): time_in_sec = int(timer[:-1]) * 60 type__ = 'minute' elif (timer[-1] == 's') and (timer.count('s') == 1): time_in_sec = int(timer[:-1]) type__ = 'second' elif (timer[-1] == 'd') and (timer.count('d') == 1): time_in_sec = int(timer[:-1]) * 86400 type__ = 'day' elif timer.isdigit(): time_in_sec = int(timer) else: await ctx.send(f"only use #s for seconds. #m for minutes. #h for hours. #d for days. ") return await ctx.message.delete() timestamp = time.time() embed = discord.Embed( title=f"TIMESTAMP TEST", timestamp=(datetime.datetime.utcfromtimestamp(timestamp)), color=0x40a0c6, description=f"**starting giveaway of {timer} {type__}(s)**'") embed.set_footer(text='__footer__') await ctx.send(embed=embed) await asyncio.sleep(time_in_sec) embed = discord.Embed( title=f"TIMESTAMP TEST", timestamp=(datetime.datetime.utcfromtimestamp(timestamp)), color=0x40a0c6, description=f"**giveaway of {timer} {type__}(s) is over!**") embed.set_footer(text='__footer__') await ctx.send(embed=embed) else: await ctx.send('**numbers only work**')
-
mongodb does not push another object instead replaces the original object data
I am making a warning system within discord.py and I got the actual data to write with the info I need, but when I run the command again it only replaces the data in the original object/warn. The point is that each warn is considered an object in the array, but it doesn't add another object for the new warn
@commands.command() @commands.guild_only() # @commands.has_guild_permissions(kick_members=True) async def warn(self, ctx, user: discord.User, *, reason=None): if user is None: await ctx.send("You have not provided a user!") return if user is user.bot: await ctx.send(f"<@{ctx.author.id}, you cannot warn a bot!") return if user.id == ctx.author.id: embed = discord.Embed(description=f"<@{ctx.author.id}>, you are not allowed to warn yourself!") embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url) embed.set_footer(text=f"{ctx.message.guild.name} Custom Designed Bot") embed.timestamp = ctx.message.created_at await ctx.send(embed=embed) return reason = reason or None _id = await self.bot.warns.find_by_id({"_id": user.id}) first_warning = True warn = { "_id": user.id, "guild": ctx.message.guild.id, "warn": [{ "PunishType": 'warn', "Moderator": ctx.message.author.id, "Reason": reason, }] } if first_warning: embed = discord.Embed(description=f"<@{ctx.author.id}>, has warned <@{user.id}> for {reason}") embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url) embed.timestamp = ctx.message.created_at await ctx.send(embed=embed) await self.bot.warns.upsert(warn) return first_warning is False elif first_warning is False: warns = await self.bot.warns.find_by_id({"_id": user.id})["warns"] newwarn = [{ "PunishType": "warn", "Moderator": ctx.author.id, "Reason": reason, }] warns.append(newwarn) await self.bot.warns.update( {"_id": "user.id"}, {"$push": {"warns": warns}})
-
Discord random number generator
I'm new to coding in python, and have started making a discord bot its just a starter project and I don't know if I'm gonna do anything with it but I wanted to make a random number generator. I'm using python 3.8.3 and pycharm here is what I tried.
import random import discord from discord.ext import commands client = commands.Bot(command_prefix=".") @client.command(pass_context = True) async def Hello(ctx): await ctx.send(random.randint(1,101)) client.run('Bot token')