Code – die besten Beiträge

Python Fehlermeldung "KeyError: 'data'"?

Ich möchte gerne einen KI Discord Server machen. Die KI hab ich schon und diese hat auch eine API(?). Ich hab den Bot auch schon auf dem Server und ich kann auch Prompts eingeben. Aber wenn ich Prompt eingebe, kommt bei diesem Code:

import discord
from gradio_client import Client


TOKEN = 'MeinToken'
FOOOCUS_API_URL = 'http://127.0.0.1:7865/'


fooocus_client = Client(FOOOCUS_API_URL)


intents = discord.Intents.default()
client = discord.Client(intents=intents)


@client.event
async def on_ready():
    print(f'{client.user} ist eingeloggt!')


@client.event
async def on_message(message):
    if message.channel.name == 'prompt-kanal' and message.author != client.user:
        result = fooocus_client.predict(message.content, fn_index=2)
        await message.channel.send(file=discord.File(result))


client.run(TOKEN)

Diese Fehlermeldung:

2024-04-16 15:35:07 ERROR discord.client Ignoring exception in on_message
Traceback (most recent call last):
File "C:...\venv\Lib\site-packages\gradio_client\compatibility.py", line 105, in _predict
output = result["data"]
~~~~~~^^^^^^^^
KeyError: 'data'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:...\venv\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:...\bot.py", line 19, in on_message
result = fooocus_client.predict(message.content, fn_index=2)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:...\venv\Lib\site-packages\gradio_client\client.py", line 459, in predict
).result()
^^^^^^^^
File "C:...\venv\Lib\site-packages\gradio_client\client.py", line 1374, in result
return super().result(timeout=timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users..._base.py", line 456, in result
return self.__get_result()
^^^^^^^^^^^^^^^^^^^
File "C:\Users..._base.py", line 401, in __get_result
raise self._exception
File "C:\Users...\thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:...\compatibility.py", line 65, in _inner
predictions = _predict(*data)
^^^^^^^^^^^^^^^
File "C:...\compatibility.py", line 119, in _predict
raise KeyError(
KeyError: 'Could not find 'data' key in response. Response received: {'detail': [{'type': 'model_attributes_type', 'loc': ['body'], 'msg': 'Input should be a valid dictionary or object to extract fields from', 'input': '{"data": [""], "fn_index": 2, "session_hash": "d7f62bf0-174c-45fe-b3f6-c5e7f00848d3"}', 'url': 'https://errors.pydantic.dev/2.1/v/model_attributes_type'}]}'

Ich checke einfach nicht, woran das liegen könnte...

Linux, Bot, cmd, Code, künstliche Intelligenz, Programmiersprache, Python, Python 3, Pycharm, Discord, Discord Bot, ChatGPT

Minecraft 1.20.4 - Eclipse Programmierung, kann keine Imports machen?

Ich möchte mit Java ein Plugin für 1.20.4 programmieren und habe mir ein Code von ChatGPT schreiben lassen.

package de.diamanthoe.plugin;

import org.bukkit.Material;

import org.bukkit.Particle;

import org.bukkit.command.Command;

import org.bukkit.command.CommandSender;

import org.bukkit.command.CommandExecutor;

import org.bukkit.configuration.ConfigurationSection;

import org.bukkit.configuration.file.FileConfiguration;

import org.bukkit.entity.Player;

import org.bukkit.inventory.Inventory;

import org.bukkit.inventory.ItemStack;

import org.bukkit.inventory.meta.ItemMeta;

import org.bukkit.plugin.java.JavaPlugin;

import org.bukkit.Location;

public class NaviSystem extends JavaPlugin implements CommandExecutor {

  @Override

  public void onEnable() {

    // Register commands

    getCommand("navi").setExecutor(this);

  }

  @Override

  public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {

    if (!(sender instanceof Player)) {

      sender.sendMessage("Dieser Befehl kann nur von Spielern ausgeführt werden.");

      return true;

    }

    Player player = (Player) sender;

    if (cmd.getName().equalsIgnoreCase("navi")) {

      if (args.length >= 1) {

        if (args[0].equalsIgnoreCase("save")) {

          if (args.length >= 2) {

            savePoint(args[1], player.getLocation());

            sender.sendMessage("Punkt gespeichert unter: " + args[1]);

          } else {

            sender.sendMessage("Verwendung: /navi save [Name]");

          }

        } else {

          if (args.length >= 3) {

            try {

              double x = Double.parseDouble(args[0]);

              double y = Double.parseDouble(args[1]);

              double z = Double.parseDouble(args[2]);

              Location target = new Location(player.getWorld(), x, y, z);

              createParticleTrail(player, target);

            } catch (NumberFormatException e) {

              sender.sendMessage("Ungültige Koordinaten.");

            }

          } else {

            sender.sendMessage("Verwendung: /navi <x y z>");

          }

        }

      } else {

        sender.sendMessage("Verwendung: /navi <x y z>");

      }

    }

    return true;

  }

  private void createParticleTrail(Player player, Location target) {

    Location playerLocation = player.getLocation();

    player.spawnParticle(Particle.REDSTONE, playerLocation, 0, target.getX(), target.getY(), target.getZ(), 10);

  }

  private void savePoint(String name, Location location) {

    FileConfiguration config = getConfig();

    config.set("points." + name + ".world", location.getWorld().getName());

    config.set("points." + name + ".x", location.getX());

    config.set("points." + name + ".y", location.getY());

    config.set("points." + name + ".z", location.getZ());

    saveConfig();

  }

  private void openPointsGUI(Player player) {

    Inventory gui = getServer().createInventory(null, 9, "Gespeicherte Punkte");

    ConfigurationSection pointsSection = getConfig().getConfigurationSection("points");

    if (pointsSection != null) {

      for (String pointName : pointsSection.getKeys(false)) {

        ConfigurationSection pointConfig = pointsSection.getConfigurationSection(pointName);

        if (pointConfig != null) {

          String worldName = pointConfig.getString("world");

          double x = pointConfig.getDouble("x");

          double y = pointConfig.getDouble("y");

          double z = pointConfig.getDouble("z");

          ItemStack pointItem = createPointItem(worldName, x, y, z);

          gui.addItem(pointItem);

        }

      }

    }

    player.openInventory(gui);

  }

  private ItemStack createPointItem(String worldName, double x, double y, double z) {

    ItemStack item = new ItemStack(Material.COMPASS);

    ItemMeta meta = item.getItemMeta();

    meta.setDisplayName(worldName + " - " + x + ", " + y + ", " + z);

    item.setItemMeta(meta);

    return item;

  }

}

Das Problem ist, dass da total viel rot unterstrichen wird, was wahrscheinlich auf die Imports zurückzuführen ist. Die Imports selbst sind teilweise ebenso rot interstrichen (org.bukkit).

Ich benutze das JDK 17 und Java SE 1.8.

Java, Minecraft, Code, Minecraft Server, Programmiersprache, Bukkit, Spigot

PHP Upload funktioniert auf PC aber nicht aufm Handy?

Hallo,

dieser Code funktioniert nicht auf Handy aber auf dem PC, hat wer tipps?

Clientseite (JavaScript):
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script></head>
<body>
<form id="fileUploadForm" enctype="multipart/form-data">
    <input type="file" name="file" id="fileInput" required>
    <button type="button" id="uploadButton">Hochladen</button>
</form>


<script>
    $(document).ready(function(){
        $('#uploadButton').on('click touchend', function(){
            var formData = new FormData($('#fileUploadForm')[0]);
            $.ajax({
                url: 'https://sub-upload.main.de/upload.php',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response){
                    console.log(response);
                    alert(response);
                },
                error: function(xhr, status, error){
                    alert(error + xhr.status);
                }
            });
        });
    });


</script>
</body>
</html>
Serverseite (upload.php):
<?php
$targetDirectory = '../uploads/';
header("Access-Control-Allow-Origin: https://sub.main.de");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");
if (!file_exists($targetDirectory)) {
    mkdir($targetDirectory, 0777, true);
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $targetFile = $targetDirectory . basename($_FILES['file']['name']);
    if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {
        echo 'Die Datei wurde erfolgreich hochgeladen.';
    } else {
        echo 'Beim Hochladen der Datei ist ein Fehler aufgetreten.';
    }
} else {
    echo 'Keine Datei zum Hochladen gefunden.';
}
?>
HTML, Webseite, JavaScript, HTML5, Code, Datenbank, JQuery, MySQL, PHP, Programmiersprache, Webdesign, Webentwicklung

Java: Methode wird sehr wahrscheinlich nicht aufgerufen?

Mein Programm lässt sich ohne jegliche Fehlermeldungen, etc. kompilieren und ausführen. Beim Ausführen des Codes stoppt es ohne einen von mir ersichtlichen Grund, wenn es die Methode karteout() ausführen soll. Es zeigt mir, wo es eigentlich einen Namen einer Spielkarte anzeigen sollte, einfach eine leere Zeile an, in die ich nichts eingeben kann.

Mein Code:

Main.java:

public class Main {
  public static void main(String[] args) {
    Kartendeck karten = new Kartendeck();
    karten.kartendeck();
    Player pturn = new Player();
    pturn.player();
  }
}

Kartendeck.java:

import java.util.Random;

public class Kartendeck {
  private int counter1;
  private int cardid;
  private int[] cards = new int[52];
  private int karte;
  private int zs1;

  public void kartendeck() {
    counter1 = -1;

    for (int i = 0; i < 4; i++) {
      for (int j = 0; j < 13; j++) {
        i++;
        j++;
        cardid = 100 * i + j;
        counter1++;
        i--;
        j--;
        cards[counter1] = cardid;
      }
    }
  }

  public void karteout() {
    Random random = new Random();
    loopkarte: while (true) {
      karte = random.nextInt(52);
      zs1 = cards[karte];

      if (cards[karte] != 0) {
        cards[karte] = 0;
        break loopkarte;
      }
    }

    if (zs1 % 100 == 1) {
      System.out.print("Ace ");
    }
    else if (zs1 % 100 == 2) {
      System.out.print("2 ");
    }
    else if (zs1 % 100 == 3) {
      System.out.print("3 ");
    }
    else if (zs1 % 100 == 4) {
      System.out.print("4 ");
    }
    else if (zs1 % 100 == 5) {
      System.out.print("5 ");
    }
    else if (zs1 % 100 == 6) {
      System.out.print("6 ");
    }
    else if (zs1 % 100 == 7) {
      System.out.print("7 ");
    }
    else if (zs1 % 100 == 8) {
      System.out.print("8 ");
    }
    else if (zs1 % 100 == 9) {
      System.out.print("9 ");
    }
    else if (zs1 % 100 == 10) {
      System.out.print("10 ");
    }
    else if (zs1 % 100 == 11) {
      System.out.print("Jack ");
    }
    else if (zs1 % 100 == 12) {
      System.out.print("Queen ");
    }
    else if (zs1 % 100 == 13) {
      System.out.print("King ");
    }
    else {
      System.out.print("");
    }

    if ((zs1 - zs1 % 100) / 100 == 1) {
      System.out.println("of Spades");
    }
    else if ((zs1 - zs1 % 100) / 100 == 2) {
      System.out.println("of Hearts");
    }
    else if ((zs1 - zs1 % 100) / 100 == 3) {
      System.out.println("of Clubs");
    }
    else if ((zs1 - zs1 % 100) / 100 == 4) {
      System.out.println("of Diamonds");
    }
    else {
      System.out.print("");
    }
  }
}

Player.java:

import java.util.Scanner;

public class Player {
  private String userinput;

  public void player() {
    Scanner scan = new Scanner(System.in);
    Kartendeck karten = new Kartendeck();
    System.out.println("CPU's up:");
    karten.karteout();
    System.out.println("Deine Startkarten:");
    karten.karteout();
    karten.karteout();

    loopturn: while (true) {
      System.out.println("Was möchtest du machen?");
      System.out.println("--> Hit");
      System.out.println("--> Stay");
      userinput = scan.nextLine();

      loopuser: while (true) {
        if (userinput.equals("Hit")) {
          karten.karteout();
          break loopuser;
        }
        else if (userinput.equals("Stay")) {
          break loopturn;
        }
        else {
          System.out.println("Diese Funktion ist nicht verfügbar!");
        }
      }
    }
  }
}

Ich hoffe, mir kann jemand helfen und vielen Dank im Voraus.

Java, Code

Meistgelesene Beiträge zum Thema Code