Discord bot json python

Вывод данных из json в discord py

Как я могу вывести все товары в embed? При попытке вывести определённый товар сталкиваюсь с такой вот ошибкой:

 Traceback (most recent call last): File "C:\Users\пк\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 167, in wrapped ret = await coro(*args, **kwargs) File "D:\Codding\! DISCORD BOTS\AlbiApi\bot.py", line 29, in allitems tovar = data['items'][0]['name'] KeyError: 'items' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\пк\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 994, in invoke await ctx.command.invoke(ctx) File "C:\Users\пк\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 894, in invoke await injected(*ctx.args, **ctx.kwargs) File "C:\Users\пк\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 176, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'items' 
@bot.command() async def allitems(ctx): await ctx.reply("Получаю все товары в донате. ") url = 'https://api.trademc.org/shop.getItems?shop=177187&v=3' response = requests.request("GET", url) data = response.json() tovar = data['items'][0]['name'] await ctx.send(embed=discord.Embed(title="", description=f"****", color = 0x2f3136)) 

Источник

Python discord bot command with json database

How would I go on doing that? edit: If I wasn’t clear I meant ho would I go on doing the python part of it?

1 Answer 1

JSON objects in python work like dictionaries.

You can write a new dictionary and save it:

data = with open("file.json", "w+") as fp: json.dump(data, fp, sort_keys=True, indent=4) # kwargs for beautification 

And you can load data from a file (this will be for updating the file):

with open("file.json", "r") as fp: data = json.load(fp) # loading json contents into data variable - this will be a dict data["foo"] = "baz" # updating values data["bar"] = "foo" # writing new values with open("file.json", "w+") as fp: json.dump(data, fp, sort_keys=True, indent=4) 

Discord.py example:

import os # for checking the file exists def add_score(member: discord.Member, amount: int): if os.path.isfile("file.json"): with open("file.json", "r") as fp: data = json.load(fp) try: data[f""]["score"] += amount except KeyError: # if the user isn't in the file, do the following data[f""] = # add other things you want to store else: data =  # saving the file outside of the if statements saves us having to write it twice with open("file.json", "w+") as fp: json.dump(data, fp, sort_keys=True, indent=4) # kwargs for beautification # you can also return the new/updated score here if you want def get_score(member: discord.Member): with open("file.json", "r") as fp: data = json.load(fp) return data[f""]["score"] @bot.command() async def cmd(ctx): # some code here add_score(ctx.author, 10) # 10 is just an example # you can use the random module if you want - random.randint(x, y) await ctx.send(f"You now have score!") 

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Quick and Easy JSON controlled Discord bot.

PersoSirEduard/JSON-DiscordBot

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Use a JSON file to control a Discord bot using the official API for Python. At its most basic functionality, by fetching the JSON file, it enables the bot the perform different actions when the user mentions specific key words that have an intend from a predefined dictionnary.

  • Respond to specific discord messages using a dictionnary of intends
  • Live modification of bot actions without the need to restart the app
  • Respond using lists (i.e. quotes, jokes, etc), texts, and files
  • Very basic message formatting directly within the JSON file
  • Add the ’embed’ response type
  • Add more formatting settings
  • Add the command action (i.e. Call the bot by using !example commands)

Python 3.8 and above is required for the application to work.

Clone the following repository:

$ git clone https://github.com/PersoSirEduard/JSON-DiscordBot.git $ cd JSON-DiscordBot

Then, install the required Python libraries:

$ python -m pip install -r requirements.txt

Configure the Discord bot

For the script to work, it requires an unique Discord token from their Developer Portal and a path/url to the commands.json file. These values can then be updated at the beginning of the main.py file. Once configured, the bot can be activated with:

Modification of the commands.json file

This next section will summarize the commands and modifications available for the bot right now.

The commands.json file is seperated into 3 main parent nodes that have a different contribution:

This section enables stores the intend dictionnary for the bot. Hence, words are associated with a intention or a concept (physical or emotional). Adding an intend to the list will require the intend to be a name and to contain an array of related words. For example, a new entry would look like this:

"ask": [ "tell", "say", "give", "answer", "buy" ],

Note: It is important to keep a strict JSON text format for the bot to read. If not, no action or command is going to work.

The uniques section is straight forward. If a specific string of text is typed, the bot will deliver a static response. To use it, a new entry would look like this:

"uniques": < "guess who's back": "Back again!" >,

In this example, if the user types «guess who’s back» in a text channel, the bot is going to reply in the same channel with «Back again!».

This following section enables the bot the perform more complexe tasks. To begin with a new action, a new dictionary must be introduced in the actions list. The name of the new object does not matter for now. Next, for the action to execute, it will need to have an array intends with the names of the intends from the intends section that we previously investigated. There is no restriction to the amount of intends the array can contain. In this manner, complexe situations can be detected by the bot if intends are set properly. This property is required for all actions up to now.

"sad_response": < "intends": ["self", "sad"], . >

Another mandatory property is the responseType which indicates to the bot what type of response to use. For now, 2 different responses are available:

  • text : Send text (formatted or not) with images and files
  • list : Query a response line from a list contained within a .txt file

Note: The order of the actions is important. Top of the list actions are first prioritized.

The text response type requires a response entry that contains a string. This string can be formatted in multiple ways:

  • $user in the response string will the replaced by the Discord user mention of the author
  • Custom variables can also be introduced in the string. They can be introduced by using %variable-name inside the string.

To introduce new variables, they need to be declared inside the responseFormat dictionary entry. For example,

"i_am_joke": < "intends": ["self"], "responseType": "text", "responseFormat": < "msg": < "extract_after_intend": "self", "upper": true > >, "response": "Hi %msg, I am dad!" >

The name of the children inside responseFormat define the name used for the variable when invoked inside the response string. This variable can then contain multiple arguments that are still developed:

  • extract_after_intend : Splits the user message text from the word from an intend dictionary and keeps the latter part of the string. The name of the used intend is required as an argument.
  • extract_before_intend : Splits the user message text from the word from an intend dictionary and keeps the former part of the string. The name of the used intend is required as an argument.
  • extract_from_intend : Extract the specific intend word from the user message text. The name of the used intend is required as an argument.
  • extract_after_string : Splits the user message text from a specified string and keeps the latter part of the string. The string sample is required as an argument.
  • extract_before_string : Splits the user message text from a specified string and keeps the former part of the string. The string sample is required as an argument.
  • lower : Lower every character from the current value of the variable. This is a boolean.
  • upper : Capitalizes every character from the current vlaue of the variable. This is a boolean.
  • exec : Execute additional Python code directly from within the input string or refer to a local file with Python code. Values ‘file’ (by default False) for a Discord file and ‘value’ (by default «») can be modified for the bot to send a text message with a file. For example,
"exec_python": < "intends": ["exec_example"], "responseType": "text", "responseFormat": < "output": < "exec": "value = 'Hello world! ' + str(random.randint(0, 100))" > >, "response": "Exec output: %output" >

Note: The order of the variable’s properties is important (order is from top to bottom).

The text response can also use the file property to send an image or a file under the limited file size offered by Discord.

Finally, the final response can be formatted inside the response property.

The list response supports text files locally and online. This response type requires a responseFile with the name of the file containing the list. Also, this response type uses responseChoice to select the item from the list to be sent to the user. By default, this property has a value of random , but an index integer can specified for a specific line from the list.

About

Quick and Easy JSON controlled Discord bot.

Источник

.get() python json file discord bot

I have a json file that stores the ids, xp and level of who writes on my server. I’m making a leaderboard to show the people who have most xp on my server, however a keyerror appears: KeyError: ‘370034734186758173’ Could someone help me fixing this error?

2 Answers 2

The .get would be used when accessing the users dictionary. You can add a second parameter to the call as the default (in case you don’t find such a key), which in the first call you should output a empty dictionary, so that the second .get doesn’t fail.

lb = list(map(lambda m: (m, users.get(m.id, <>).get("xp"), message.server.members)) 

Since you are making a list out of it, you may also want to try (the somewhat more pythonic) list comprehension (not that your line has anything wrong with it):

lb = [ (m, users.get(m.id, <>).get("xp") for m in message.server.members ] 

Note that both approaches will return a None item when the get doesn’t find the Key in the dictionary, you can ommit this using an if clause in the list comprehension:

lb = [ (m, users.get(m.id, <>).get("xp") for m in message.server.members if m.id in users ] 

As a side note, I would add that you have included everything within the context manager clause ( with open(): ), while only the line where you load its contents is necessary. It would be best practice to de-indent the rest of your code.

Источник

Читайте также:  Поля класса java что это
Оцените статью