This repository has been archived by the owner on Apr 28, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Reika.rb
233 lines (182 loc) · 6.42 KB
/
Reika.rb
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
# frozen_string_literal: true
require 'addressable'
require 'faraday'
require 'discordrb'
require 'active_support'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/filters'
require 'active_support/core_ext/numeric/conversions'
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/integer/time'
require 'active_support/core_ext/date'
require 'date'
require 'json'
require 'uri'
require 'pry-byebug'
RequiredEnvVars = %w[DISCORD_TOKEN STEAM_API_KEY STEAM_IMG_PROXY_HOST]
if RequiredEnvVars.any? {|name| ENV[name].blank? }
raise NotImplementedError, "you need to specify environment variables: #{RequiredEnvVars.join(', ')}"
end
CitiesAppID = 255710
DynoID = '155149108183695360'
bot = Discordrb::Bot.new(
token: ENV['DISCORD_TOKEN'],
ignore_bots: true,
)
WorkshopURL = Addressable::Template.new(
'{http,https}://steamcommunity.com/{sharedfiles,workshop}/filedetails/{?id,params*}'
)
SteamImageProxyURL = Addressable::Template.new(
"https://#{ENV['STEAM_IMG_PROXY_HOST']}/{type}/{arg0}/{arg1}/image.jpg?interpolation=lanczos-none&output-format=jpeg&output-quality=95&fit=inside%7C128%3A128&composite-to=*,*%7C128%3A128&background-color=black&extension=jpeg"
)
class SteamAPI
APIKey = ENV['STEAM_API_KEY']
Endpoint = Addressable::URI.parse('https://api.steampowered.com')
EndpointTemplate = Addressable::Template.new(
"{resource}/{target}/{version}/"
)
SteamUser = EndpointTemplate.partial_expand(resource: 'ISteamUser')
RemoteStorage = EndpointTemplate.partial_expand(resource: 'ISteamRemoteStorage')
def initialize
@conn = Faraday.new(url: Endpoint)
end
def PlayerSummaries(ids)
ids = Array.wrap(ids)
@conn.get SteamUser.expand(target: 'GetPlayerSummaries', version: 'v2'), {
key: APIKey,
steamids: ids.join(','),
}
end
def PublishedFileDetails(ids)
ids = Array.wrap(ids)
@conn.post RemoteStorage.expand(target: 'GetPublishedFileDetails', version: 'v1'), {
itemcount: ids.length
}.merge(Hash[
ids.map.with_index {|id, i| ["publishedfileids[#{i}]", id] }
])
end
end
def sanitize_d(text)
text.gsub(/`/, '\\\\`')
end
def preview_url_parts(url)
_, type, *args = Pathname.new(Addressable::URI.parse(url).path).to_s.split(File::SEPARATOR)
case type
when 'ugc'
{
type: type,
arg0: args[0],
arg1: args[1],
}
else
raise NotImplementedError, "Steam URL type `#{type}` is not supported"
end
end
bot.message do |ev|
api = SteamAPI.new
urls = URI.extract(ev.message.text).uniq
ignored_urls = urls.select {|url|
ev.message.text.to_s.include? "<#{url.to_s}>"
}
# puts urls, ignored_urls
urls.each do |url_raw|
next if ignored_urls.include?(url_raw)
url = Addressable::URI.parse(url_raw)
params = WorkshopURL.extract(url)
next unless params
puts "[message] #{ev.user.name} (#{ev.user.id}): #{ev.message}"
j = JSON.parse(api.PublishedFileDetails(Integer(params['id'])).body)
j['response']['publishedfiledetails'].each do |item|
next unless item['visibility'] == 0
next if item['banned'] != 0
ev.channel.send_embed do |embed|
# item['description'] = ''
tags = item['tags'].map {|e| e['tag']}
embed.color = tags.include?('Mod') ? '#ff71ef' : '#ff9153'
embed.title = "#{item['title']}"
desc = item['description']
urls_in_desc = URI.extract(desc).uniq
urls_in_desc.each do |url|
desc.gsub!(url, '')
end
embed.description = desc
.gsub(/\n|\r\n/, ' ')
.gsub(/\[\/?[^\]]+?\]/, ' ')
.gsub(/`/, '\\`')
.gsub(/[:@]/, '`\1`')
.gsub(/\s+/, ' ')
.truncate(200, separator: /\p{Zs}/, omission: ' ...')
embed.thumbnail = Discordrb::Webhooks::EmbedThumbnail.new(
url: SteamImageProxyURL.expand(preview_url_parts(item['preview_url'])).to_s
)
embed.url = url
creator = JSON.parse(api.PlayerSummaries(item['creator']).body)['response']['players'][0]
# puts creator
embed.add_field(
name: ":white_check_mark: **#{item['subscriptions'].to_s(:delimited)}**",
value: [
":hearts: **#{item['favorited'].to_s(:delimited)}**",
":eye: **#{item['views'].to_s(:delimited)}**",
].join(' '),
inline: true
)
name = "#{sanitize_d(creator['personaname'])}"
realname = creator['realname'].present? ? "(#{sanitize_d(creator['realname'])})" : ''
embed.author = Discordrb::Webhooks::EmbedAuthor.new(
name: [name, realname].join(' '),
url: creator['profileurl'],
icon_url: creator['avatar'],
)
# embed.add_field(
# name: [':spy:'].compact.join(' '),
# value: [name, realname, flag].join(' '),
# inline: true,
# )
# flag = creator['loccountrycode'].present? ? ":flag_#{sanitize_d(creator['loccountrycode']).downcase}:" : nil
updated = Time.at(item['time_updated']).to_datetime
updatedDelta = (DateTime.now - updated).to_i
updatedDeltaL = \
case updatedDelta
when 0
"Today"
when 1
"Yesterday"
else
"#{updatedDelta} days ago"
end
embed.add_field(name: ":file_folder: **\`#{item['file_size'].to_s(:human_size)}\`**", value: ":tools: Last update: #{updatedDeltaL}#{updatedDelta <= 7 ? ' :new:' : ''}", inline: true)
embed.timestamp = Time.at(item['time_created'])
embed.footer = Discordrb::Webhooks::EmbedFooter.new(
text: tags.map {|tag| sanitize_d(tag) }.join(', ')
)
end
end
# puts j
end
end
def to_emoji(args)
Array.wrap(args).map {|arg| ":#{arg}:" }
end
bot.mention do |ev|
next unless ev.message.mentions.any? {|u| u.current_bot? }
content = ev.message.content.sub(/^<@#{bot.profile.id}>\s+/, '')
# binding.pry
case content
when /意気込み/
ev.channel.send_message "<@#{DynoID}> あんたには負けないんだから"
when /(?:ちゅっ?)+/, /#{to_emoji(%w[peropero oppai ashi eroi]).join('|')}/
ev.channel.send_message "<@#{ev.user.id}> 二度とわたしに話しかけないで"
when /#{to_emoji(%w[kawaii]).join('|')}/, /かわいい|kawaii|可爱/
ev.channel.send_message "<@#{ev.user.id}> 知ってる。"
else
next
end
puts ev.message.content
end
loop do
begin
bot.run
rescue => e
puts e
end
end