11from discord .ext import commands
2+ import os
3+ import random
4+ import asyncio
25
36class Giveaway (commands .Cog ):
47
58 def __init__ (self , client ):
69 self .bot = client
10+ admin_role = os .getenv ("ADMIN_ROLE" )
711
12+ def convert (time ):
13+ pos = ["s" ,"m" ,"h" ,"d" ]
14+
15+ time_dict = {"s" : 1 , "m" : 60 , "h" : 3600 , "d" : 3600 * 24 }
16+
17+ unit = time [- 1 ]
18+
19+ if unit not in pos :
20+ return - 1
21+ try :
22+ val = int (time [:- 1 ])
23+ except :
24+ return - 2
25+
26+
27+ return val * time_dict [unit ]
28+
29+ @commands .command ()
30+ @commands .has_role ()
31+ async def giveaway (ctx ):
32+ await ctx .send ("Let's start with this giveaway! Answer these questions within 15 seconds!" )
33+
34+ questions = ["Which channel should it be hosted in?" ,
35+ "What should be the duration of the giveaway? (s|m|h|d)" ,
36+ "What is the prize of the giveaway?" ]
37+
38+ answers = []
39+
40+ def check (m ):
41+ return m .author == ctx .author and m .channel == ctx .channel
42+
43+ for i in questions :
44+ await ctx .send (i )
45+
46+ try :
47+ msg = await client .wait_for ('message' , timeout = 15.0 , check = check )
48+ except asyncio .TimeoutError :
49+ await ctx .send ('You didn\' t answer in time, please be quicker next time!' )
50+ return
51+ else :
52+ answers .append (msg .content )
53+ try :
54+ c_id = int (answers [0 ][2 :- 1 ])
55+ except :
56+ await ctx .send (f"You didn't mention a channel properly. Do it like this { ctx .channel .mention } next time." )
57+ return
58+
59+ channel = client .get_channel (c_id )
60+
61+ time = convert (answers [1 ])
62+ if time == - 1 :
63+ await ctx .send (f"You didn't answer the time with a proper unit. Use (s|m|h|d) next time!" )
64+ return
65+ elif time == - 2 :
66+ await ctx .send (f"The time must be an integer. Please enter an integer next time" )
67+ return
68+
69+ prize = answers [2 ]
70+
71+ await ctx .send (f"The Giveaway will be in { channel .mention } and will last { answers [1 ]} !" )
72+
73+
74+ embed = discord .Embed (title = "Giveaway!" , description = f"{ prize } " , color = ctx .author .color )
75+
76+ embed .add_field (name = "Hosted by:" , value = ctx .author .mention )
77+
78+ embed .set_footer (text = f"Ends { answers [1 ]} from now!" )
79+
80+ my_msg = await channel .send (embed = embed )
81+
82+
83+ await my_msg .add_reaction (":tada:" )
84+
85+
86+ await asyncio .sleep (time )
87+
88+
89+ new_msg = await channel .fetch_message (my_msg .id )
90+
91+
92+ users = await new_msg .reactions [0 ].users ().flatten ()
93+ users .pop (users .index (client .user ))
94+
95+ winner = random .choice (users )
96+
97+ await channel .send (f"Congratulations! { winner .mention } won { prize } !" )
898
999def setup (client ):
10100 client .add_cog (Giveaway (client ))
0 commit comments