forked from thesecretmaster/ips-comment-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
comment_scan.rb
283 lines (253 loc) · 10.2 KB
/
comment_scan.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
require "se/api"
require "chatx"
require 'uri'
require 'logger'
require 'time'
require 'yaml'
require './db'
require 'pry-byebug'
IO.write("bot.pid", Process.pid.to_s)
start = Time.now
manual_scan = []
sleeptime = 0
settings = File.exists?('./settings.yml') ? YAML.load_file('./settings.yml') : ENV
post_on_startup = ARGV[0].to_i || 0
cb = ChatBot.new(settings['ChatXUsername'], settings['ChatXPassword'])
cli = SE::API::Client.new(settings['APIKey'], site: settings['site'])
HQ_ROOM_ID = settings['hq_room_id'].to_i
ROOMS = settings['rooms']
cb.login
cb.say("_Starting at rev #{`git rev-parse --short HEAD`.chop} on branch #{`git rev-parse --abbrev-ref HEAD`.chop} (#{`git log -1 --pretty=%B`.gsub("\n", '')})_", HQ_ROOM_ID)
cb.join_room HQ_ROOM_ID
cb.join_rooms ROOMS #THIS IS THE PROBLEM
BOT_NAMES = settings['names'] || Array(settings['name'])
def matches_bot(bot)
puts "Checking if #{bot} matches #{BOT_NAMES}"
bot.nil? || bot == '*' || BOT_NAMES.include?(bot.downcase)
end
ROOMS.each do |room_id|
Room.find_or_create_by(room_id: room_id)
end
def on?(room_id)
Room.find_by(room_id: room_id).on
end
cb.gen_hooks do
ROOMS.each do |room_id|
room room_id do
command "!!/off" do |bot|
if matches_bot(bot) && on?(room_id)
say "Turning off..."
Room.find_by(room_id: room_id).update(on: false)
end
end
command "!!/whoami" do
if on?(room_id)
say "I go by #{BOT_NAMES.join(" and ")}"
end
end
command "!!/mode" do |bot|
if matches_bot(bot) && on?(room_id)
say "I'm in child mode. My parent is in [room #{HQ_ROOM_ID}](https://chat.stackexchange.com/rooms/#{HQ_ROOM_ID})"
end
end
command "!!/on" do |bot|
if matches_bot(bot) && !on?(room_id)
say "Turning on..."
Room.find_by(room_id: room_id).update(on: true)
end
end
command "!!/notify" do |bot, type, status|
if matches_bot(bot) && on?(room_id)
act = {
"regex" => :regex_match,
"magic" => :magic_comment
}[type]
status = {"on" => true, "off" => false}[status]
say "I #{status ? "will" : "won't"} notify you on a #{act}" unless status.nil? || act.nil?
Room.find_by(room_id: room_id).update(**{act => status}) unless status.nil? || act.nil?
end
end
command "!!/reports" do |bot|
if matches_bot(bot) && on?(room_id)
room = Room.find_by(room_id: room_id)
say "regex_match: #{!!room.regex_match}\nmagic_comment: #{!!room.magic_comment}"
end
end
command "!!/regexes" do |bot|
say(Regex.all.map { |r| "#{r.post_type}: #{r.regex}" }.join("\n")) if matches_bot(bot) && on?(room_id)
end
command "!!/alive" do |bot|
if matches_bot(bot) && on?(room_id)
say "I'm alive and well :)"
end
end
command "!!/help" do |bot|
say File.read("./help.txt") if matches_bot(bot) && on?(room_id)
end
end
end
room HQ_ROOM_ID do
command("!!/whoami") { |bot| say (rand(0...20) == rand(0...20) ? "24601" : "I go by #{BOT_NAMES.join(" and ")}") }
command("!!/alive") { |bot| say "I'm alive!" if matches_bot(bot) }
command("!!/help") { |bot| say(File.read('./hq_help.txt')) if matches_bot(bot) }
command("!!/quota") { |bot| say "#{cli.quota} requests remaining" if matches_bot(bot) }
command("!!/uptime") { |bot| say Time.at(Time.now - start).strftime("Up %H hours, %M minutes, %S seconds") if matches_bot(bot) }
command "!!/logsize" do |bot|
if matches_bot(bot)
say(Dir['*.log*'].map do |log|
log_file = "./#{log}"
fsize, ext = File.size(log_file).to_f/(1024**2), "MB"
fsize, ext = File.size(log_file).to_f/(1024**2), "GB" if fsize > 1024
"#{log}: #{fsize.round(2)}#{ext}" if File.exist? log_file
end.join("\n"))
end
end
command("!!/howmany") { |bot| say "I've scanned #{Comment.count} comments" if matches_bot(bot) }
command "!!/test" do |bot, type, *body|
if matches_bot(bot)
say "Unknown post type '#{type}'" unless %w[q a].include? type[0]
say(report(type, body.join(" ")) || "Didn't match any filters")
end
end
command "!!/add" do |bot, type, regex, *reason|
if matches_bot(bot) && r = Reason.find_or_create_by(name: reason.join(' ')).regexes.create(post_type: type[0], regex: regex)
say "Added regex #{r.regex} for post_type #{r.post_type} with reason '#{r.reason.name}'"
end
end
command "!!/del" do |bot, type, regex, *reason|
if matches_bot(bot)
if r = Regex.find_by(post_type: type[0], regex: regex)
say "Destroyed #{r.regex} (post_type #{r.post_type})!" if r.destroy
else
say "Could not find regex to destroy"
end
end
end
command "!!/cid" do |bot, cid|
if matches_bot(bot)
c = Comment.find_by(comment_id: cid)
if c
say c.body_markdown
else
say "Could not find comment with id #{cid}"
end
end
end
command "!!/pull" do |bot, *args|
if matches_bot(bot)
`git pull`
Kernel.exec("bundle exec ruby comment_scan.rb #{args.empty? ? post_on_startup : args[0].to_i}")
end
end
command "!!/restart" do |bot, *args|
if matches_bot(bot)
Kernel.exec("bundle exec ruby comment_scan.rb #{args.empty? ? post_on_startup : args[0].to_i}")
end
end
command("!!/kill") { |bot| `kill -9 $(cat bot.pid)` if matches_bot(bot) }
command("!!/rev") { |bot| say "Currently at rev #{`git rev-parse --short HEAD`.chop} on branch #{`git rev-parse --abbrev-ref HEAD`.chop}" if matches_bot(bot) }
command "!!/manscan" do |*args|
manual_scan += cli.comments(args)
end
command("!!/mode") { |bot| say "I'm in parent mode. I have children in rooms #{ROOMS.map { |rid| "[#{rid}](https://chat.stackexchange.com/rooms/#{rid})"}.join(", ")}" if matches_bot(bot) }
command("!!/ttscan") { |bot| say "#{sleeptime} seconds remaning until the next scan" if matches_bot(bot) }
end
end
comments = cli.comments[0..-1]
@last_creation_date = comments[post_on_startup].json["creation_date"].to_i+1 unless comments[post_on_startup].nil?
@logger = Logger.new('msg.log')
def ts_for(ts)
return "" if ts.nil?
ts = (Time.new - Time.at(ts.to_i)).to_i
return "" if ts < 0
if ts < 60
"#{ts} seconds ago"
elsif ts/60 < 60
"#{ts/60} minutes ago"
elsif ts/(60**2) < 60
"#{ts/(60**2)} hours ago"
else
"#{ts/(24*60*60)} days ago"
end
end
def user_for(author)
return "" unless author.is_a? SE::API::User
name = author.name
link = author.link&.gsub(/(^.*u[sers]{4}?\/\d*)\/.*$/, '\1')&.gsub("/users/", "/u/")
rep = author.reputation
return "(deleted user)" if name.nil? && link.nil? && rep.nil?
"[#{name}](#{link}) (#{rep} rep)"
end
def record_comment(comment)
return false unless comment.is_a? SE::API::Comment
c = Comment.new
%i[body body_markdown comment_id creation_date edited link post_id post_type score].each do |f|
c.send(:"#{f}=", comment.send(f))
end
c.save unless Comment.exists?(c.attributes.reject { |_k,v| v.nil? })
end
def report(post_type, comment)
regexes = Regex.where(post_type: post_type[0].downcase)
matching_regexes = regexes.select do |regex|
%r{#{regex.regex}}.match? comment.downcase
end
return "Matched regex(es) #{matching_regexes.map { |r| r.reason.nil? ? r.regex : r.reason.name }.uniq }" unless matching_regexes.empty?
end
def has_magic_comment?(comment, post)
!comment.body_markdown.include?("https://interpersonal.meta.stackexchange.com/q/1644/31") &&
post.comments.any? do |c|
c.body_markdown.include?("https://interpersonal.meta.stackexchange.com/q/1644/31")
end
end
sleep 1 # So we don't get chat errors for 3 messages in a row
loop do
comments = cli.comments(fromdate: @last_creation_date) + manual_scan
manual_scan = []
@last_creation_date = comments[0].json["creation_date"].to_i+1 unless comments[0].nil?
puts comments.length
comments.each do |comment|
author = comment.owner
base = "https://#{URI(author.link).host}"
author_link = "[#{author.name}](#{base}/u/#{author.id})"
body = comment.json["body_markdown"]
rep = "#{author.reputation} rep"
max_len = 200
date = Time.at(comment.json["creation_date"].to_i)
seconds = (Time.new - date).to_i
ts = seconds < 60 ? "#{seconds} seconds ago" : "#{seconds/60} minutes ago"
post = cli.posts(comment.json["post_id"])[0]
author = user_for post.owner
editor = user_for post.last_editor
creation_ts = ts_for post.json["creation_date"]
edit_ts = ts_for post.json["last_edit_date"]
type = post.type[0].upcase
cb.say(comment.link, HQ_ROOM_ID)
msg = "##{post.json["post_id"]} #{user_for(comment.owner)} | [#{type}: #{post.title}](#{post.link}) (score: #{post.score}) | posted #{creation_ts} by #{author}"
msg += " | edited #{edit_ts} by #{editor}" unless edit_ts.empty? || editor.empty?
# msg += " | @Mithrandir (has magic comment)" if !(comment.body_markdown.include?("https://interpersonal.meta.stackexchange.com/q/1644/31") && comment.owner.id == 31) && post.comments.any? { |c| c.body_markdown.include?("https://interpersonal.meta.stackexchange.com/q/1644/31") && c.user.id.to_i == 31 }
msg += " | Has magic comment" if has_magic_comment? comment, post
cb.say(msg, HQ_ROOM_ID)
report_text = report(post.type, comment.body_markdown)
cb.say(report_text, HQ_ROOM_ID) if report_text
ROOMS.each do |room_id|
room = Room.find_by(room_id: room_id)
if room.on
if room.on && ((room.magic_comment && has_magic_comment?(comment, post)) || (room.regex_match && report_text))
cb.say(comment.link, room_id)
cb.say(msg, room_id)
cb.say(report_text, room_id) if room.regex_match && report_text
end
end
end
@logger.info "Parsed comment:"
@logger.info "(JSON) #{comment.json}"
@logger.info "(SE::API::Comment) #{comment.inspect}"
@logger.info "Current time: #{Time.new.to_i}"
#rval = cb.say(comment.link, 63296)
#cb.delete(rval.to_i)
#cb.say(msg, 63296)
record_comment(comment)
end
sleeptime = 60
while sleeptime > 0 do sleep 1; sleeptime -= 1 end
end