-
Notifications
You must be signed in to change notification settings - Fork 7
/
raffle.go
111 lines (84 loc) · 2.3 KB
/
raffle.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
"errors"
"fmt"
"math/rand"
"sync"
"time"
"github.com/bwmarrin/discordgo"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
var (
ulock sync.Mutex
raffleUsers = map[string]map[string]struct{}{}
raffleSessions = map[string]string{}
)
func raffleStart(s *discordgo.Session, m *discordgo.Message, parv []string) error {
ulock.Lock()
defer ulock.Unlock()
raffleSessions[m.ChannelID] = m.Author.ID
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("<@%s> created a new raffle! Type %senter to enter!", m.Author.ID, ";"))
return nil
}
func rafflePop(s *discordgo.Session, m *discordgo.Message, parv []string) error {
ulock.Lock()
defer ulock.Unlock()
creator, ok := raffleSessions[m.ChannelID]
if !ok {
return errors.New("no raffle currently running")
}
if m.Author.ID != creator {
return fmt.Errorf("you are not <@%s>, you cannot select a winner", creator)
}
cmap, ok := raffleUsers[m.ChannelID]
if !ok {
cmap = map[string]struct{}{}
}
users := []string{}
for u := range cmap {
users = append(users, u)
}
i := rand.Intn(len(users))
u := users[i]
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("Congrats <@%s>, you won!", u))
delete(cmap, u)
raffleUsers[m.ChannelID] = cmap
return nil
}
func raffleEnd(s *discordgo.Session, m *discordgo.Message, parv []string) error {
ulock.Lock()
defer ulock.Unlock()
creator, ok := raffleSessions[m.ChannelID]
if !ok {
return errors.New("no raffle currently running")
}
if m.Author.ID != creator {
return fmt.Errorf("you are not <@%s>, you cannot end this raffle", creator)
}
delete(raffleUsers, m.ChannelID)
delete(raffleSessions, m.ChannelID)
s.ChannelMessageSend(m.ChannelID, "Raffle destroyed.")
return nil
}
func raffle(s *discordgo.Session, m *discordgo.Message, parv []string) error {
ulock.Lock()
defer ulock.Unlock()
_, ok := raffleSessions[m.ChannelID]
if !ok {
return errors.New("no raffle currently running")
}
cmap, ok := raffleUsers[m.ChannelID]
if !ok {
cmap = map[string]struct{}{}
}
_, ok = cmap[m.Author.ID]
if ok {
return errors.New("you already joined this raffle, you can't join it again")
}
cmap[m.Author.ID] = struct{}{}
raffleUsers[m.ChannelID] = cmap
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("<@%s>: your entry has been recorded!", m.Author.ID))
return nil
}