Discord.py变量

2024-05-06 12:10:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个Discordbot,它让我可以使用jsonapi查找有关IP地址的信息。但是,我在配置文件(ip=config.get(“ip”)中定义了ip.现在我想做的是,sues可以在命令后将IP作为参数传递,然后只要进程正在运行,给定的IP应该临时存储到变量中,然后在发送嵌入后,它应该从变量中删除IP。如果有人能帮我,那就太好了

import discord
import requests
import json
from discord.ext import commands

with open("config.json") as config:
    config = json.load(config)
    developer = config.get("Developer")
    token = config.get("Token")
    appid = config.get("ApplicationID")
    prefix = config.get("Prefix")
    apikey = config.get("API-KEY")
    ipadress = config.get("IP-Adress")

    bot = commands.Bot(command_prefix=prefix, Intents=discord.Intents.all(), help_command=None)
    response = requests.get(f"https://api.ipgeolocation.io/ipgeo?apiKey={apikey}&ip={ipadress}")


    def jprint(obj):
        # create a formatted string of the Python JSON object
        text = json.dumps(obj, sort_keys=True, indent=4)
        print(text)

    # jprint(response.json())
call_code = response.json()["calling_code"]
city = response.json()["city"]
connection_type = response.json()["connection_type"]
continent_code = response.json()["continent_code"]
continent_name = response.json()["continent_name"]
country_capital = response.json()["country_capital"]
country_code2 = response.json()["country_code2"]
country_code3 = response.json()["country_code3"]
country_name = response.json()["country_name"]
country_tld = response.json()["country_tld"]
currency = response.json()["currency"]
currency_code = response.json()["currency"]["code"]
currency_name = response.json()["currency"]["name"]
currency_symbol = response.json()["currency"]["symbol"]
district = response.json()["district"]
geoname_id = response.json()["geoname_id"]
ip = response.json()["ip"]
is_eu = response.json()["is_eu"]
isp = response.json()["isp"]
languages = response.json()["languages"]
latitude = response.json()["latitude"]
longitude = response.json()["longitude"]
organization = response.json()["organization"]
state_prov = response.json()["state_prov"]
time_zone = response.json()["time_zone"]
time_zone_name = response.json()["time_zone"]["name"]
time_zone_offset = response.json()["time_zone"]["offset"]
time_zone_current_time = response.json()["time_zone"]["current_time"]
time_zone_current_time_unix = response.json()["time_zone"]["current_time_unix"]
time_zone_is_dst = response.json()["time_zone"]["is_dst"]
time_zone_dst_savings = response.json()["time_zone"]["dst_savings"]
zipcode = response.json()["zipcode"]


@bot.command(name="location")
async def geolookup(ctx, args: ip):
    embed = discord.Embed(
        title="Location Lookup:",
        description="Outputs a lot of Infos about  a IP",
        color=0xFF0C93)

    embed.add_field(
        name="Calling-Code: ",
        value=f"{call_code}",
        inline=True)

    embed.add_field(
        name="City: ",
        value=f"{city}",
        inline=True)

    embed.add_field(
        name="Continent-Code: ",
        value=f"{continent_code}",
        inline=True)

    embed.add_field(
        name="Continent-Name: ",
        value=f"{continent_name}",
        inline=True)

    embed.add_field(
        name="Country-Capital: ",
        value=f"{country_capital}",
        inline=True)

    embed.add_field(
        name="Country-Code2: ",
        value=f"{country_code2}",
        inline=True)

    embed.add_field(
        name="Country-Code3: ",
        value=f"{country_code3}",
        inline=True)

    embed.add_field(
        name="Country-Name: ",
        value=f"{country_name}",
        inline=True)

    embed.add_field(
        name="Country-TLD: ",
        value=f"{country_tld}",
        inline=True)

    embed.add_field(
        name="Currency: ",
        value=f"Code: {currency_code} \n"
              f"Name: {currency_name} \n"
              f"Symbol: {currency_symbol}", inline=True)

    embed.add_field(
        name="District: ",
        value=f"{district}",
        inline=True)

    embed.add_field(
        name="Geoname-ID: ",
        value=f"{geoname_id}",
        inline=True)

    embed.add_field(
        name="IP: ",
        value=f"{args}",
        inline=True)

    embed.add_field(
        name="IS-EU: ",
        value=f"{is_eu}",
        inline=True)

    embed.add_field(
        name="ISP: ",
        value=f"{isp}",
        inline=True)

    embed.add_field(
        name="Languages: ",
        value=f"{languages}",
        inline=True)

    embed.add_field(
        name="Latitude: ",
        value=f"{latitude}",
        inline=True)

    embed.add_field(
        name="Longitude: ",
        value=f"{longitude}",
        inline=True)

    embed.add_field(
        name="Organization: ",
        value=f"{organization}",
        inline=True)

    embed.add_field(
        name="State-Prov: ",
        value=f"{state_prov}",
        inline=True)

    embed.add_field(
        name="Time-Zone: ",
        value=f"Name: {time_zone_name} \n"
              f"Offset: {time_zone_offset} \n"
              f"Current Time: {time_zone_current_time} \n"
              f"Current Time Unix: {time_zone_current_time_unix} \n"
              f"is_dst: {time_zone_is_dst}\n"
              f"dst_savings: {time_zone_dst_savings}", inline=True)

    embed.add_field(
        name="Zipcode: ",
        value=f"{zipcode}",
        inline=True)

    embed.set_footer(text=f"Created by {developer}")
    embed.set_thumbnail(url=ctx.author.avatar_url)
    await ctx.channel.send(embed=embed)


@bot.event
async def on_ready():
    print("Ready!")


bot.run(token, reconnect=True)

Tags: nameaddconfigjsontruezonefieldtime
1条回答
网友
1楼 · 发布于 2024-05-06 12:10:17

您正在使用的^{}扩展可以轻松地添加带有参数的命令

命令中参数的参考:discord.py docs

from discord.ext import commands

bot = commands.Bot(command_prefix='$')

@bot.command(name="greet")
async def test(ctx, arg1):
    # Do something with arg1
    embed = Embed(
            title=f"Hello {arg1}",
            color=0x00A61D,
        )

    await ctx.send(embed=embed)

将请求代码放入函数中,并从discord命令调用该函数

def get_ip_details(ip_address):
    response = requests.get(
        f"https://api.ipgeolocation.io/ipgeo",
        params={"apiKey":"apikey", "ip":"ip_address"}
    )
    # Check if response
    response.check_for_status()
    ip_data = {
        "call_code": response["calling_code"],
        "city": response["city"],
        "connection_type": response["connection_type"],
        "continent_code": response["continent_code"],
        "continent_name": response["continent_name"],
        "country_capital": response["country_capital"],
        "country_code2": response["country_code2"],
        "country_code3": response["country_code3"],
        "country_name": response["country_name"],
        "country_tld": response["country_tld"],
        "currency": response["currency"],
        "currency_code": response["currency"]["code"],
        "currency_name": response["currency"]["name"],
        "currency_symbol": response["currency"]["symbol"],
        "district": response["district"],
        "geoname_id": response["geoname_id"],
        "ip": response["ip"],
        "is_eu": response["is_eu"],
        "isp": response["isp"],
        "languages": response["languages"],
        "latitude": response["latitude"],
        "longitude": response["longitude"],
        "organization": response["organization"],
        "state_prov": response["state_prov"],
        "time_zone": response["time_zone"],
        "time_zone_name": response["time_zone"]["name"],
        "time_zone_offset": response["time_zone"]["offset"],
        "time_zone_current_time": response["time_zone"]["current_time"],
        "time_zone_current_time_unix": response["time_zone"]["current_time_unix"],
        "time_zone_is_dst": response["time_zone"]["is_dst"],
        "time_zone_dst_savings": response["time_zone"]["dst_savings"],
        "zipcode": response["zipcode"],
    }




现在,您可以从命令函数调用ip_地址函数

@bot.command(name="location")
async def get_ip_location(ctx, ip_address):
    try:
        ip_details = get_ip_details(ip_address)

        <ip_details is a dict with all the data>
        <add details to embed here>

        await ctx.send(embed=embed)
    except Exception:
        await ctx.send("Error fetching details")    


您还可以指定intbool或任何其他可调用函数作为参数的类型,它将尝试将参数转换为该类型

您可以通过文档的Converters部分获得更多详细信息


其他建议

  1. 您可以使用pprint模块来打印漂亮的内容。您不需要jprint函数
  2. 您可以将response.json()保存到变量中,然后从中获取所有这些值。您不需要每次都调用response.json()
  3. 使用aiohttp而不是requests,以便可以异步发出请求
  4. 您可以直接将字符串传递到嵌入中,而不是仅对字符串使用f字符串

相关问题 更多 >