iT邦幫忙

2021 iThome 鐵人賽

DAY 25
0
自我挑戰組

Discord-bot,從0開始到做出一個機器人系列 第 26

小物件實作

鬧鐘

# cogs/......略
@commands.command()
async def clock(self, ctx, mins, todo):
    embed = discord.Embed(title = "提醒", description = f"您已預約了{mins}分鐘後提醒您", color = 0x4599) 
    embed.set_thumbnail(url = "https://www.formula-ai.com/wp-content/uploads/2020/09/python_or_java_meme.jpg")
    await ctx.send(embed = embed)
    time.sleep(int(mins) * 60)
    sms =  discord.Embed(title = "時間到", description = f"您剛剛預約了{mins}分鐘要{todo},現在時間已經到囉", color = 0x4599)
    sms.set_thumbnail(url = "https://www.formula-ai.com/wp-content/uploads/2020/09/python_or_java_meme.jpg")
    await ctx.message.author.send(embed = sms)
  • 示意圖

訂單功能

  • 目標如下
    1. 打開json檔看user.id是否存在
    2. 如果不存在就建立
    3. 存在就添加及改寫
@commands.command()
async def plus(self, ctx, nums):
    if nums == None:
        return 
    nums = int(nums)
  • check
# 打開json檔看user.id是否存在 
async def read_data():    
    with open("bank.json", "r")as file:            
        users = json.load(file)
    return users          
  • read_data
# 如果不存在就建立    
async def open_account(user):
    users = await read_data()
    if str(user.id) in users:
        return False
    else:
        users[str(user.id)] = {}
        users[str(user.id)]["貨物量"] = 0
    
    with open("plus.json", "w") as f:
        json.dump(users, f)
        
    return True 
  • reset
# 存在就添加及改寫
async def reset(user, change = 0, mode = "amount"):
    users = await read_data()
    users[str(user.id)][mode] += change

    with open("plus.json", "w") as f:
        json.dump(users, f)
    bal = [users[str(user.id)]["amount"]]    
    return bal
  • 這些都是從前面的功能稍微做一些更動,就可以直接使用了
  • 接下來加上添加元素,前面一樣有範例程式碼喔~~
  • 讀取資料
users = await read_data()
to_count = {}
total = []
for user in users:
    name = int(user)
    total_amount = users[user]["amount"]
    to_count[total_amount] = name
    total.append(total_amount)
  • 資料排序
total = sorted(total, reverse = True)
  • 元素添加
embed = discord.Embed(title = "這次的量", description = "將訂貨量排序後的結果呈現", color = 0x5568)
embed.set_thumbnail(url = "https://www.formula-ai.com/wp-content/uploads/2020/09/python_or_java_meme.jpg")
for i in total:
    userid = to_count[i]
    member = await bot.fetch_user(userid)
    name = member.name
    embed.add_field(name = f"{name}", value = f"您訂購的數量為{i}", inline = False)
    
await ctx.send(embed = embed)
  • 示意圖

上一篇
終極密碼DC版
下一篇
統整先前的小缺漏
系列文
Discord-bot,從0開始到做出一個機器人30

尚未有邦友留言

立即登入留言