xia的小窩

一起來coding和碼字吧

0%

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

鬧鐘(可以用tasks實做)

1
2
3
4
5
6
7
8
9
10
# 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)

示意圖

訂單功能

目標如下

  • 打開json檔看user.id是否存在
  • 如果不存在就建立
  • 存在就添加及改寫

這邊就呼叫一下

1
2
3
4
5
@commands.command()
async def plus(self, ctx, nums):
if nums == None:
return
nums = int(nums)

check

1
2
3
4
5
# 打開json檔看user.id是否存在 
async def read_data():
with open("bank.json", "r")as file:
users = json.load(file)
return users

read_data

1
2
3
4
5
6
7
8
9
10
11
12
13
# 如果不存在就建立    
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

1
2
3
4
5
6
7
8
9
# 存在就添加及改寫
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

這些都是從前面的功能稍微做一些更動,就可以直接使用了
接下來加上添加元素,前面一樣有範例程式碼喔~~

進行讀取資料

1
2
3
4
5
6
7
8
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)

資料排序

1
total = sorted(total, reverse = True)

元素添加

1
2
3
4
5
6
7
8
9
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)

示意圖