@a5rocks/

Code Jam #8

Python

No description

fork
loading
Files
  • main.py
  • quale
  • requirements.txt
main.py
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
from quale import Gateway, CommandHandler
from trio import run, open_nursery, sleep
from pymongo import MongoClient
from os import getenv
import json
from pprint import pprint

# configs are for wimps
STAR_REACTION = '⭐'
MINIMUM_STARS = 1
STARBOARD_NAME = 'starboard'  # after end

# use a "database" they said.
# so i did.
database = MongoClient(getenv('MONGODB_URL')).starboat

commander = CommandHandler('pls ', 'snip ', edit=True, mentions=True)



@commander.register(name='ping')
async def ping_pong(message):
  heartbeat = message.gateway.heartbeat

  await message.respond(':ping_pong: `{:04.2f}ms`'.format(heartbeat))

@commander.register(name='eval')
async def evaluate(message):
  if message.author_id != 302968847353249813:
    return

  try:
    await message.respond(str(eval(message.clean_message[5:])))
  except Exception as e:
    await message.respond(str(e))

@commander.listen('MESSAGE_CREATE')
async def update_databases(data, gateway):
  # check if this is a dm
  if not data.get('guild_id'):
    return
  
  star_count = 0
  if data.get('reactions'):
    for reaction in data.get('reactions', []):
      if reaction.get('emoji', {}).get('name') == STAR_REACTION:
        star_count = reaction.get('count', 0)
  
  # insert a new message into the message database
  try:
    database.messages.insert_one({'_id': str(data['id']), 'author': data['author']['id'], 'contents': data.get('content') or 'embedded', 'stars': star_count, 'p_name': str(data['author']['username']) + '#' + str(data['author']['discriminator'])})
  except Exception as e:
    raise e
  
  # update the "updates" document
  try:
    database.updates.update_one({'_id': data['guild_id']}, {'$set': {str(data['channel_id']): str(data['id'])}})
  except Exception as e:
    raise e


@commander.listen('MESSAGE_REACTION_ADD')
async def update_stars(data, gateway):
  # check if this is a dm
  if not data.get('guild_id'):
    return
  
  database.messages.update_one({'_id':str(data['message_id'])}, {'$inc': {'stars': 1}})

  current_message = database.messages.find_one({'_id':str(data['message_id'])})
  current_stars = current_message.get('stars', 0)

  if current_stars >= MINIMUM_STARS:
    starboard_id = database.updates.find_one({'_id':data['guild_id']})['starboard']

    starboard_message = database.starboard.find_one({'_id':str(data['message_id'])})

    message = current_message
    if not starboard_message:
      message_id = json.loads((await gateway.http_client.send(starboard_id, embed={
        'title': 'Starred Message',
        'description': message['contents'],
        'author': {
          'name': message['p_name'],
          # todo: 'icon_url' = avatar
        },
        'footer': {
          'text': '{} {}'.format(STAR_REACTION, message['stars'])
        }
      })).content.decode('utf-8'))['id']
      try:
        database.starboard.insert_one({'_id':message['_id'], 'm_id': message_id})
      except:
        pass  # whatever /shrug

    else:
      await gateway.http_client.update_message(starboard_id, starboard_message['m_id'], new_embed={
        'title': 'Starred Message',
        'description': message['contents'],
        'author': {
          'name': message['p_name'],
          # todo: 'icon_url' = avatar
        },
        'footer': {
          'text': '{} {}'.format(STAR_REACTION, message['stars'])
        }
      })

      try:
        database.starboard.update_one({'_id':str(data['message_id'])}, {'$inc': {'stars': 1}})
      except: 
        pass  # whatever /shrug
      
  # todo: leaderboards


@commander.listen('MESSAGE_REACTION_REMOVE')
async def update_stars(data, gateway):
  # check if this is a dm
  if not data.get('guild_id'):
    return
  
  database.messages.update_one({'_id':str(data['message_id'])}, {'$inc': {'stars': -1}})

  current_message = database.messages.find_one({'_id':str(data['message_id'])})
  current_stars = current_message.get('stars', 0)

  if current_stars < MINIMUM_STARS:
    starboard_id = database.updates.find_one({'_id':data['guild_id']})['starboard']

    starboard_message = database.starboard.find_one({'_id':str(data['message_id'])})

    await gateway.http_client.delete_message(starboard_id, starboard_message['m_id'])

    database.starboard.remove_one({'_id':str(data['message_id'])})


@commander.listen('MESSAGE_REACTION_REMOVE')
async def update_negative_stars(data, gateway):
  # check if this is a dm
  if not data.get('guild_id'):
    return
  
  database.messages.update_one({'_id':str(data['message_id'])}, {'$inc': {'stars': -1}})
  # todo: leaderboards

async def get_channel_messages(channel, gateway, starboard_id, after=None, reverse=False):
  messages = await gateway.http_client.get_messages(channel['id'], after=after)
  past_message_id = after
  bulk_write_list = []
  starboard_worthy = []
  

  while len(messages) > 0:
    for message in messages:
      star_count = 0
      if message.get('reactions'):
        for reaction in message.get('reactions', []):
          if reaction.get('emoji', {}).get('name') == STAR_REACTION:
            star_count = reaction.get('count', 0)

      bulk_write_list.append({'_id': str(message['id']), 'author': message['author']['id'], 'contents': message.get('content') or 'embedded', 'stars': star_count, 'p_name': str(message['author']['username']) + '#' + str(message['author']['discriminator'])})
      
      if star_count >= MINIMUM_STARS:
        starboard_worthy.append({'_id': str(message['id']), 'author': message['author']['id'], 'contents': message.get('content') or 'embedded', 'stars': star_count, 'p_name': str(message['author']['username']) + '#' + str(message['author']['discriminator'])})

        
    await sleep(0.2)
    
    if reverse:
      past_message_id = messages[0]['id']
      messages = await gateway.http_client.get_messages(channel['id'], after=past_message_id)
    else:
      past_message_id = messages[-1]['id']
      messages = await gateway.http_client.get_messages(channel['id'], before=past_message_id)
  
  if bulk_write_list != []:
    try:
      database.messages.insert_many(bulk_write_list, ordered=False)
    except:
      print('well theres an exception with mongodb... who cares ;)')
  
  for message in starboard_worthy:
    message_id = json.loads((await gateway.http_client.send(starboard_id, embed={
      'title': 'Starred Message',
      'description': message['contents'],
      'author': {
        'name': message['p_name'],
        # todo: 'icon_url' = avatar
      },
      'footer': {
        'text': '{} {}'.format(STAR_REACTION, message['stars'])
      }
    })).content.decode('utf-8'))['id']

    try:
      database.starboard.insert_one({'_id':message['_id'], 'm_id': message_id})
    except:
      pass  # whatever /shrug

    await sleep(1)  # can't spam the api, now can we?

  return past_message_id
  


# get new guild messages
@commander.listen('GUILD_CREATE')
async def get_guild_messages(data, gateway):
  # first, confirm a starboard channel exists:
  starboard_id = None
  for channel in data['channels']:
    #if channel['name'] == 'starboard':
    if channel['name'] == STARBOARD_NAME:  # after end
      starboard_id = channel['id']
  
  if not starboard_id:
    #starboard_id = await gateway.http_client.create_channel(data['id'], 'starboard')
    starboard_id = await gateway.http_client.create_channel(data['id'], STARBOARD_NAME)  # after end
  
  if starboard_id == None:
    return
  
  update_table = database.updates.find_one({'_id': data['id']}) or {'_id': data['id'], 'starboard': str(starboard_id)}

  for channel in data['channels']:
    if str(channel['id']) not in update_table.keys() or update_table[str(channel['id'])] == None:
      update_table[str(channel['id'])] = await get_channel_messages(channel, gateway, starboard_id)
    else:
      update_table[str(channel['id'])] = await get_channel_messages(channel, gateway, starboard_id, update_table[str(channel['id'])], True)
    
  database.updates.replace_one({'_id': data['id']}, update_table, upsert=True)


gateway = Gateway(getenv('TEST_TOKEN'), command_handler=commander,
initial_presence={
  'game': {
    'name': 'with stars',
    'type': 0
  }
})

# starter
async def main():
  async with open_nursery() as nursery:
    await gateway.start(nursery)

run(main)