Discord Bot – die neusten 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

Raspberry PI Flask-404 Not Found?

Hallo!

Ich habe das programmiert. Es wird jede Sekunde die Temperatur von der CPU ausgelesen. Jetzt möchte ich Flask einbauen, damit ich mit mehreren PC's darauf zugreifen kann. Aber es funktioniert nicht. Warum?

from flask import Flask, jsonify
import subprocess
import time
import os
from colorama import Fore, Style

app = Flask(__name__)

@app.route("/temp")
def get_cpu_temperature():
  try:
    result = subprocess.run(['vcgencmd', 'measure_temp'], capture_output=True, text=True, check=True)
    temperature_str = result.stdout.strip()
    temperature = float(temperature_str[5:-2]) # Extrahiere die Temperatur aus dem String
    return temperature
  except subprocess.CalledProcessError as e:
    print(f"Fehler beim Ausführen des Befehls: {e}")
    return None

def print_colored_temperature(temperature):
  if temperature is not None:
    if temperature > 49.9:
      print(f"{Fore.RED}Temperatur: {temperature}°C{Style.RESET_ALL}")
    else:
      print(f"Temperatur: {temperature}°C")
  else:
    print("Fehler beim Lesen der CPU-Temperatur.")

def main():
  try:
    while True:
      temperature = get_cpu_temperature()
      print_colored_temperature(temperature)
      time.sleep(1)
      os.system('clear')
  except KeyboardInterrupt:
    print("Programm wurde durch den Benutzer unterbrochen.")
  except Exception as e:
    print(f"Ein Fehler ist aufgetreten: {e}")
     
     


if __name__ == '__main__':
  app.run(host="0.0.0.0")

if __name__ == '__main__':
  main()
  import sys
  sys.exit(main(sys.argv))  
HTML, Code, Programmiersprache, Python, Python 3, Pycharm, Discord, Flask, Discord Bot, ChatGPT

Nodejs mariadb Column count doesn't match value count at row 1?

meine datenbank hat 4 spalten aber ich setze nur 3 ein weil die letzte eine auto_increment spalte ist,

ich nutze nodejs mit mariadb und habe folgende fehlermeldung beim daten einsetzen:

/home/j44/Downloads/themer/tut/node_modules/mariadb/lib/misc/errors.js:64
  return new SqlError(msg, sql, fatal, info, sqlState, errno, additionalStack, addHeader);
         ^

SqlError: (conn=2420, no: 1136, SQLState: 21S01) Column count doesn't match value count at row 1
sql: INSERT INTO thread value (no, head, ts) - parameters:['1171187570193989762','rrrrrrrrrrrrrrrr',1699303276347]
    at module.exports.createError (/home/j44/Downloads/themer/tut/node_modules/mariadb/lib/misc/errors.js:64:10)
    at PacketNodeEncoded.readError (/home/j44/Downloads/themer/tut/node_modules/mariadb/lib/io/packet.js:582:19)
    at Query.readResponsePacket (/home/j44/Downloads/themer/tut/node_modules/mariadb/lib/cmd/parser.js:58:28)
    at PacketInputStream.receivePacketBasic (/home/j44/Downloads/themer/tut/node_modules/mariadb/lib/io/packet-input-stream.js:85:9)
    at PacketInputStream.onData (/home/j44/Downloads/themer/tut/node_modules/mariadb/lib/io/packet-input-stream.js:135:20)
    at Socket.emit (node:events:514:28)
    at addChunk (node:internal/streams/readable:376:12)
    at readableAddChunk (node:internal/streams/readable:349:9)
    at Readable.push (node:internal/streams/readable:286:10)
    at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
  sqlMessage: "Column count doesn't match value count at row 1",
  sql: "INSERT INTO thread value (no, head, ts) - parameters:['1171187570193989762','rrrrrrrrrrrrrrrr',1699303276347]",
  fatal: false,
  errno: 1136,
  sqlState: '21S01',
  code: 'ER_WRONG_VALUE_COUNT_ON_ROW'
}


SQL, programmieren, JavaScript, Datenbank, MySQL, node.js, Discord, Discord Bot

Discord ticket bot Öffnet kein ticket?

Wenn ich versuche ein neues ticket zu öffnen Kommt in discord der fehler: "Diese Interaktion ist fehlgeschlagen und im code-editor kommt die Fehlermeldung: "Traceback (most recent call last):

 , line 427, in _scheduled_task

  await item.callback(interaction)

, line 35, in ticket

  await interaction.defer(

AttributeError: 'Button' object has no attribute 'defer'

import discord

from discord.ext import commands

TOKEN = "DISCORD-BOTTOKEN"

bot = commands.Bot(command_prefix="!",

                   intents=discord.Intents.all(),

                   status=discord.Status.dnd)

async def change_bot_activity():

    activity = discord.Activity(type=discord.ActivityType.watching, name="")

    await bot.change_presence(activity=activity)

@bot.event

async def on_ready():

    print("Bot is Ready!")

    await change_bot_activity()

@bot.command(name="ticket")

@commands.has_permissions(administrator=True)

async def ticket(ctx):

    embed = discord.Embed(

        description="Drück den Button, um ein neues Ticket zu erstellen!"

    )

    view = CreateButton()

    await ctx.send(embed=embed, view=view)

class CreateButton(discord.ui.View):

    def __init__(self):

        super().__init__(timeout=None)

    @discord.ui.button(label="Create Ticket", style=discord.ButtonStyle.blurple, emoji="🎫", custom_id="ticketopen")

    async def ticket(self, button: discord.ui.Button, interaction: discord.Interaction):

        # Nutzerinteraktion bestätigen

        await interaction.defer()

        category = discord.utils.get(interaction.guild.categories, id=)

        for ch in category.text_channels:

            if ch.topic == f"{interaction.user.id} DO NOT CHANGE THE TOPIC OF THIS CHANNEL":

                await interaction.followup.send("Du hast bereits ein Ticket: {0}".format(ch.mention), ephemeral=True)

                return

        r1 = discord.utils.get(interaction.guild.roles, id=)

        overwrites = {

            interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),

            r1: discord.PermissionOverwrite(read_messages=True, send_messages=True, manage_messages=True),

            interaction.user: discord.PermissionOverwrite(read_messages=True, send_messages=True),

            interaction.guild.me: discord.PermissionOverwrite(read_messages=True, send_messages=True)

        }

        channel = await category.create_text_channel(

            name=str(interaction.user),

            topic=f"{interaction.user.id} DO NOT CHANGE THE TOPIC OF THIS CHANNEL!",

            overwrites=overwrites

        )

        await channel.send(embed=discord.Embed(

            title="Ticket erstellen",

            description="Pinge keine Teammitglieder",

            color=discord.Color.green()

        ))

        await interaction.followup.send(

            embed=discord.Embed(

                description="Erstelle ein neues Ticket {0}".format(channel.mention),

                color=discord.Color.white()

            )

        )

bot.run(TOKEN)

Bot, Programmiersprache, Python, Python 3, Discord, Discord Bot

Meistgelesene Beiträge zum Thema Discord Bot