-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsfrbot.py
1160 lines (1113 loc) · 59.1 KB
/
sfrbot.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
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import csv
import datetime
import discord
import logging
import os
import sqlite3
import urllib.request
from beem import Steem
from beem.account import Account
from beem.comment import Comment
from beem.exceptions import AccountDoesNotExistsException, ContentDoesNotExistsException, VotingInvalidOnArchivedPost
from beem.instance import set_shared_steem_instance
from beem.nodelist import NodeList
from beem.utils import construct_authorperm, addTzInfo
from collections import defaultdict
from discord.ext.commands import Bot
import matplotlib.pyplot as plt #for future use
import sfr_config as cfg
import sfr_config as cfg
class RangeDict(dict):
def __getitem__(self, item):
if type(item) != range:
for key in self:
if item in key:
return self[key]
else:
return super().__getitem__(item)
logging.basicConfig(level=logging.INFO, filename=cfg.LOGFILE)
db = sqlite3.connect(cfg.DATABASEFILE)
cursor = db.cursor()
nodes = NodeList().get_nodes()
stm = Steem(node=nodes)
set_shared_steem_instance(stm)
queueing = False
##################################################
# Uncomment for the initial setup of the database
# cursor.execute('''CREATE TABLE steemflagrewards
# (flagger TEXT, comment TEXT, post TEXT, category TEXT, created TEXT, included BOOL, payout REAL, queue BOOL, weight REAL, followon BOOL, dust BOOL default '0', approved_by TEXT, mod_included BOOL, flag_rshares INTEGER, paid BOOL)''')
# cursor.execute('CREATE TABLE flaggers (name TEXT)')
# cursor.execute('CREATE TABLE sdl (name TEXT, created TEXT, delegation BOOL)')
# cursor.execute('CREATE TABLE sfr_posts (post TEXT, created TEXT)')
# db.commit()
##################################################
# Uncomment for initial setup of Plotly credential file using env variable
# plotly.tools.set_credentials_file(username=cfg.plotlyuser, api_key=os.getenv('PLOTLY'))
##################################################
def get_abuse_categories(comment_body):
"""Returning the matching categories of abuse"""
cats = []
body = comment_body.lower()
for cat in sorted(cfg.CATEGORIES.keys()):
if cat in body:
# distinguish between the overlapping categories "spam"
# and "comment spam"
if cat == 'spam' and 'comment spam' in body:
continue
cats.append(cat)
return cats
def get_approval_comment_body(flagger, abuse_categories, dust=False):
""" assemble the body for the flag approval comment """
cat_string = ''
try:
cat_string = ''.join([cfg.CATEGORIES[cat] for cat in abuse_categories])
except KeyError:
print('Key error grabbing category with '+str(abuse_categories))
logging.info('Key error grabbing category with '+str(abuse_categories))
if dust is True:
body = 'Steem Flag Rewards mention comment has been approved ' \
'for flagger beneficiary post rewards! ' \
'Thank you for reporting this abuse, @{}.\n{}\n\n' \
'This post was submitted via our Discord Community channel. ' \
'Check us out on the following link!\n[SFR Discord]({})'.format(
flagger, cat_string, cfg.DISCORD_INVITE)
else:
body = 'Steem Flag Rewards mention comment has been approved! ' \
'Thank you for reporting this abuse, @{}.\n{}\n\n' \
'This post was submitted via our Discord Community channel. ' \
'Check us out on the following link!\n[SFR Discord]({})'.format(
flagger, cat_string, cfg.DISCORD_INVITE)
return body
def get_rewards_chart(removed, remaining):
labels = ['Rewards Removed','Rewards Remaining']
values = [removed,remaining]
trace = go.Pie(labels=labels, values=values) #create pie chart
try:
charturl = py.plot([trace], filename='flagger_pie_chart_'+str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")), auto_open=True) #upload pie chart
except Exception as e:
print("Chart error")
print(e)
return
charturl += ".png"
return charturl
def get_wait_time(account):
"""Get the time (in seconds) required until the next comment can be posted.
Only works for one 'queued' comment.
"""
account.refresh()
last_post_timedelta = addTzInfo(datetime.datetime.utcnow()) - account['last_post']
return max(0, cfg.STEEM_MIN_REPLY_INTERVAL - last_post_timedelta.total_seconds())
def build_mod_report_body(flag_table):
""" assemble the 8-flagges report post body """
body = '## This post triggers once the SteemFlagRewards Moderation Team Reviews and Approves 50 ' \
'flag mention comments via the SteemFlagRewards Abuse Fighting Community on our ' \
'[Discord]({})\n\nhttps://cdn.steemitimages.com/' \
'DQmfREGg6Kr1vVi6sbM711ZfahMmb8FpzTWJvDbM7oLmTjW/sfr-mod-fund-steemseph.jpg\n\n' \
'Moderators have been designated as post beneficiaries based on # of approvals.' \
' Our mods have put in a lot of charitable work and effort ' \
'to enrich the blockchain by reviewing flags. ' \
' Please, consider following this account to track this activity \n' \
'and help reward it accordingly. Feel free to review the flags for ' \
'quality and let us know how we are doing! \n' \
'### Would you like to delegate to the Steem Flag Rewards project ' \
'and promote decentralized moderation? ' \
'Here are some handy delegation links!\n'.format(cfg.DISCORD_INVITE)
for amount in [50, 100, 500, 1000]:
body += " [{} SP](https://steemconnect.com/sign/" \
"delegateVestingShares?delegator=&" \
"delegatee={}&vesting_shares=" \
"{}%20SP)".format(amount, cfg.SFRACCOUNT, amount)
if len(cfg.WITNESSES):
body += '\n\nThe following witnesses are providing significant delegations to support the SFR mission. ' \
'Please consider giving them your vote for witness. ' \
'Steemconnect links included for convenience.\n'
for wtn in cfg.WITNESSES:
body += "* [{}](https://v2.steemconnect.com/sign/account-" \
"witness-vote?witness={}&approve=1)\n".format(wtn, wtn)
if len(cfg.OTHERWITNESS):
body += '\n\nThe following witnesses have shown considerable support and dedication against abuse. ' \
'Please consider giving them your vote for witness. ' \
'Steemconnect links included for convenience.\n'
for wtn in cfg.OTHERWITNESS:
body += "* [{}](https://v2.steemconnect.com/sign/account-" \
"witness-vote?witness={}&approve=1)\n".format(wtn, wtn)
if len(cfg.SUPPORTERS):
list_of_supporters = ", ".join(["@{}".format(user) for user in
cfg.SUPPORTERS])
body += '\n\nThe following have shown considerable support and / or dedication to the cause and ' \
'deserve a mention. Check out their blogs if you have the ' \
'opportunity!\n{}'.format(list_of_supporters)
body += '\n\n\n{}'.format(flag_table)
body += '\n\n\n <hr><div class="pull-left"><a href="https://discordapp.com/invite/fmE7Q9q"></a></div> If you feel you\'ve been wrongly flagged, check out @freezepeach, the flag abuse neutralizer. See the <a href="https://steemit.com/introduceyourself/@freezepeach/freezepeach-the-flag-abuse-neutralizer">intro post</a> for more details, or join the <a href="https://discordapp.com/invite/fmE7Q9q">discord server.</a><hr>'
return body
def build_report_body(flag_table):
""" assemble the 8-flagges report post body """
body = '## This post triggers once we have approved flags from 8 distinct ' \
'flaggers via the SteemFlagRewards Abuse Fighting Community on our ' \
'[Discord]({})\n\n https://ipfs.busy.org/ipfs/' \
'QmPCPE97dB7HZjqWkmiKiSuuZUjy2AfUw64ZuLsVRLqvN4\n\n' \
'Flaggers have been designated as post beneficiaries. Our goal is ' \
'to empower abuse fighting Steemians and promote a ' \
'platform that is less-friendly to abuse. It is simple. Building ' \
'abuse fighters equals less abuse.\n'\
'### Would you like to delegate to the Steem Flag Rewards project ' \
'and promote decentralized moderation? ' \
'Here are some handy delegation links!\n'.format(cfg.DISCORD_INVITE)
for amount in [50, 100, 500, 1000]:
body += " [{} SP](https://steemconnect.com/sign/" \
"delegateVestingShares?delegator=&" \
"delegatee={}&vesting_shares=" \
"{}%20SP)".format(amount, cfg.SFRACCOUNT, amount)
if len(cfg.WITNESSES):
body += '\n\nThe following witnesses are providing significant delegations to support the SFR mission. ' \
'Please consider giving them your vote for witness. ' \
'Steemconnect links included for convenience.\n'
for wtn in cfg.WITNESSES:
body += "* [{}](https://v2.steemconnect.com/sign/account-" \
"witness-vote?witness={}&approve=1)\n".format(wtn, wtn)
if len(cfg.OTHERWITNESS):
body += '\n\nThe following witnesses have shown considerable support and dedication against abuse. ' \
'Please consider giving them your vote for witness. ' \
'Steemconnect links included for convenience.\n'
for wtn in cfg.OTHERWITNESS:
body += "* [{}](https://v2.steemconnect.com/sign/account-" \
"witness-vote?witness={}&approve=1)\n".format(wtn, wtn)
if len(cfg.SUPPORTERS):
list_of_supporters = ", ".join(["@{}".format(user) for user in
cfg.SUPPORTERS])
body += '\n\nThe following have shown considerable support and / or dedication to the cause and ' \
'deserve a mention. Check out their blogs if you have the ' \
'opportunity!\n{}'.format(list_of_supporters)
body += '\n\n\n{}'.format(flag_table)
return body
def flag_leaderboard():
rank_list = []
rank_dict = {}
rank_markdown = ''
sql = cursor.execute('SELECT flagger, sum(flag_rshares), count(flag_rshares) FROM steemflagrewards GROUP BY flagger ORDER BY sum(flag_rshares) ASC LIMIT 20')
for q in sql.fetchall():
sbd_amount = stm.rshares_to_sbd(abs(q[1]))
rank_list.append({
'Downvoter': q[0],
'Total Flags': q[2],
'rshares': q[1],
'sbd_amount': round(sbd_amount,3),
'Rank': cfg.class_rank_dict[abs(q[1])],
'Image': cfg.class_img_dict[abs(q[1])]
})
export_csv('sfr',rank_list)
rank_list = sorted(rank_list, key=lambda k: k['rshares'],reverse=False)
rank_markdown += '\n # SFR Leaderboard \n'
rank_markdown += '|Flagger|SBD Amount|Rank|Image|\n|:-----------:|:---------:|:--------|:--------:|'
for leader in rank_list:
rank_markdown += '\n|{}|{}|{}|{}|'.format(leader['Downvoter'],str(leader['sbd_amount'])+" SBD", leader['Rank'], leader['Image'])
return rank_markdown
def export_csv(name,votelist):
cwd = os.getcwd()
filename=datetime.datetime.now().strftime(name+"%Y%m%d-%H%M%S.csv")
keys = votelist[0].keys()
outfile=open(cwd+'/'+filename,'w')
writer=csv.DictWriter(outfile, keys)
writer.writeheader()
writer.writerows(votelist)
def export_sfr_db():
sql = cursor.execute('SELECT * FROM steemflagrewards')
sfrdb = sql.fetchall()
slist = []
sdict = {}
for s in sfrdb:
sdict = {
'flagger': s[0],
'comment': s[1],
'post': s[2],
'category': s[3],
'created': s[4],
'included': s[5],
'payout': s[6],
'queue': s[7],
'weight': s[8],
'followon': s[9],
'dust': s[10],
'approved_by': s[11],
'mod_included': s[12],
'flag_rshares': s[13],
'paid': s[14]
}
slist.append(sdict)
export_csv('sfr_db_export',slist)
return slist
def insert_mention(approving_mod_steem_acct,cats,dust,flagger, flaggers_comment,flagged_post, sfrdvote, weight, queueing):
included = False
follow_on = False #column to be removed. follow on flag data will be archived
paid = False
mod_included = False
cursor.execute('INSERT INTO steemflagrewards VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (
flagger.name, flaggers_comment.authorperm, flagged_post.authorperm, ', '.join(cats),
flaggers_comment['created'], included,
stm.rshares_to_sbd(sfrdvote['rshares']), queueing, weight, follow_on, dust, approving_mod_steem_acct, mod_included, int(sfrdvote['rshares']),paid))
db.commit()
def mod_leaderboard():
cfg.mod_list = []
rank_dict = {}
rank_markdown = ''
sql = cursor.execute("SELECT approved_by, count(approved_by) FROM steemflagrewards WHERE approved_by NOT IN ('None', 'steemflagrewards') GROUP BY approved_by ORDER BY count(approved_by) DESC")
for q in sql.fetchall():
cfg.mod_list.append({
'Mod': q[0],
'Total Approvals': q[1],
'Mod Rank': cfg.mod_rank_dict[abs(q[1])],
'Image': cfg.mod_img_dict[abs(q[1])]
})
cfg.mod_list = sorted(cfg.mod_list, key=lambda k: k['Total Approvals'],reverse=True)
rank_markdown += '\n # SFR Mod Leaderboard \n'
rank_markdown += '|Mod|Total Approvals|Mod Rank|Image|\n|:-----------:|:---------:|:--------|:--------:|'
for leader in cfg.mod_list:
rank_markdown += '\n|{}|{}|{}|{}|'.format(leader['Mod'],str(leader['Total Approvals']), leader['Mod Rank'], leader['Image'])
return rank_markdown
def mod_report():
"""Posting a mod report post with the moderators set as beneficiaries."""
sql_list = []
flagged_post_data = []
sql = cursor.execute(
"SELECT CASE WHEN category LIKE '%nsfw%' OR category LIKE '%porn spam%' THEN '[NSFW link](https://steemit.com/' || post || '#' || comment || ')' " \
"ELSE '[Comment](https://steemit.com/\' || post || '#' || comment || ')' END, '@' || approved_by, category, post, comment, " \
"CASE WHEN category LIKE '%nsfw%' OR category LIKE '%porn spam%' THEN '[NSFW link](https://steemit.com/' || post || ')' " \
"ELSE '[Comment](https://steemit.com/\' || post || ')' END " \
"FROM steemflagrewards WHERE cfg.mod_included == 0 AND approved_by IN (SELECT approved_by FROM steemflagrewards WHERE cfg.mod_included == 0 LIMIT 8)" \
"LIMIT 50;")
for q in sql.fetchall():
sql_list.append(q)
sql_flaggable = cursor.execute( #Queries obtains flagged posts within the 5 day mark for report includsion and action
"SELECT DISTINCT CASE WHEN category LIKE '%nsfw%' OR category LIKE '%porn spam%' THEN '[NSFW link](https://steemit.com/' || post || '#' || comment || ')' " \
"ELSE '[Comment](https://steemit.com/\' || post || '#' || comment || ')' END, '@' || approved_by, category, post, comment, " \
"CASE WHEN category LIKE '%nsfw%' OR category LIKE '%porn spam%' THEN '[NSFW link](https://steemit.com/' || post || ')' " \
"ELSE '[Comment](https://steemit.com/\' || post || ')' END " \
"FROM steemflagrewards WHERE created > DATETIME(\'now\', \'-5 days\')")
table = 'Flaggable Posts \n |Link|Rewards Remaining|Category|\n|:----|:----------------:|:--------|'
for q in sql_flaggable.fetchall():
flagged_post_dict = {}
try:
flagged_comment = Comment(q[3])
pending_payout = flagged_comment['pending_payout_value']
except Exception as e:
print('Was unable to obtain pending payout value on https://steemit.com/'+str(q[3]))
logging.exception(e)
pending_payout = "Null"
flagged_post_dict = {'link': q[5], 'payout': pending_payout.amount, 'category': q[2]}
flagged_post_data.append(flagged_post_dict)
flagged_post_data = sorted(flagged_post_data, key=lambda k: k['payout'],reverse=True)
flagged_post_data = [dict(tupleized) for tupleized in set(tuple(item.items()) for item in flagged_post_data)]
for fpd in flagged_post_data:
if fpd['payout'] >0:
table += '\n|{}|{}|{}|'.format(fpd['link'],str(fpd['payout'])+" SBD", fpd['category'])
table += '\n --- \n'
table1 = '|Link|Approved By|Category|\n|:-----------|:---------------:|:--------|'
for q in sql_list:
table1 += '\n|{}|{}|{}|'.format(q[0], q[1], q[2])
body = build_cfg.mod_report_body(table)
body += '\n\n\n{}'.format(table1)
sql_active = cursor.execute(
"SELECT sum(flag_rshares), sum(payout) FROM steemflagrewards WHERE created > DATETIME(\'now\', \'-7 days\')")
q = sql_active.fetchone()
removed = stm.rshares_to_sbd(float(q[0]))
remain = q[1]
body += "\n --- "
try:
body += get_rewards_chart(abs(removed),abs(remain))
except Exception as e:
print(e)
success_ratio = round((abs(removed)/(abs(remain)+abs(removed))*100),2)
if(success_ratio >= 70):
body +="\n# Mission Accomplished! \n"
body +=" http://img200.imageshack.us/img200/3750/missionaccomplishedl.jpg "
else:
body +="\n# Mission Failed! \n"
body +=" https://static.giantbomb.com/uploads/original/0/329/1195180-psd3d036.jpg "
body += "Active SFR Flag Mention Reward removal at: "+str(success_ratio)+" % \n"
body += cfg.mod_leaderboard()
body += '\n\n\n <hr><div class="pull-left"><a href="https://discordapp.com/invite/fmE7Q9q"></a></div> If you feel you\'ve been wrongly flagged, check out @freezepeach, the flag abuse neutralizer. See the <a href="https://steemit.com/introduceyourself/@freezepeach/freezepeach-the-flag-abuse-neutralizer">intro post</a> for more details, or join the <a href="https://discordapp.com/invite/fmE7Q9q">discord server.</a><hr>'
logging.info('Generated post body')
benlist = []
approvals = []
approvers = []
for q in sql_list:
approvals.append(str(q[1]).replace('@',''))#extracts username from tuple
approvers = set(approvals)
for approver in approvers:
benlist.append({'account': approver, 'weight': int(approvals.count(approver)/len(approvals)*9900)})
benlist= sorted(benlist, key=lambda k: k['account'],reverse=False)
rep = stm.post(
'Steem Flag Rewards Mod Report - Moderator Post - {}'.format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")),
body, 'sfr-mod-fund', tags=['steemflagrewards', 'abuse', 'steem', 'flag', 'busy'], beneficiaries=benlist,
parse_body=True, self_vote=False, community='busy', app='busy/2.5.6')
for s in sql_list:
query = cursor.execute('UPDATE steemflagrewards SET mod_included = 1 WHERE comment == ?',(s[4],))
db.commit()
return construct_authorperm(rep['operations'][0][1])
def report():
"""Posting a report post with the flaggers set as beneficiaries."""
sql_list = []
flagged_post_data = []
cursor.execute('DELETE FROM flaggers;')
cursor.execute(
'INSERT INTO flaggers SELECT DISTINCT flagger FROM steemflagrewards WHERE included == 0 ORDER BY created ASC LIMIT 8;')
sql = cursor.execute(
"SELECT CASE WHEN category LIKE '%nsfw%' OR category LIKE '%porn spam%' THEN '[NSFW link](https://steemit.com/' || post || '#' || comment || ')' " \
"ELSE '[Comment](https://steemit.com/\' || post || '#' || comment || ')' END, '@' || flagger, category, post, comment, " \
"CASE WHEN category LIKE '%nsfw%' OR category LIKE '%porn spam%' THEN '[NSFW link](https://steemit.com/' || post || ')' " \
"ELSE '[Comment](https://steemit.com/\' || post || ')' END " \
"FROM steemflagrewards WHERE included == 0 AND flagger IN flaggers;")
for q in sql.fetchall():
sql_list.append(q)
sql_flaggable = cursor.execute( #Queries obtains flagged posts within the 5 day mark for report includsion and action
"SELECT DISTINCT CASE WHEN category LIKE '%nsfw%' OR category LIKE '%porn spam%' THEN '[NSFW link](https://steemit.com/' || post || '#' || comment || ')' " \
"ELSE '[Comment](https://steemit.com/\' || post || '#' || comment || ')' END, '@' || flagger, category, post, comment, " \
"CASE WHEN category LIKE '%nsfw%' OR category LIKE '%porn spam%' THEN '[NSFW link](https://steemit.com/' || post || ')' " \
"ELSE '[Comment](https://steemit.com/\' || post || ')' END " \
"FROM steemflagrewards WHERE created > DATETIME(\'now\', \'-5 days\')")
db.commit()
table = '### Flaggable Posts \n |Link|Rewards Remaining|Category|\n|:----|:------------|:--------|'
for q in sql_flaggable.fetchall():
flagged_post_dict = {}
flag_list = []
try:
flagged_post = Comment(q[3])
pending_payout = flagged_post['pending_payout_value']
except Exception as e:
print('Was unable to obtain pending payout value on https://steemit.com/'+str(q[3]))
logging.exception(e)
pending_payout = 0.000
flagged_post_dict = {'link': q[5], 'payout': pending_payout.amount or 0.000, 'category': q[2]}
flagged_post_data.append(flagged_post_dict)
flagged_post_data = sorted(flagged_post_data, key=lambda k: k['payout'],reverse=True)
flagged_post_data = [dict(tupleized) for tupleized in set(tuple(item.items()) for item in flagged_post_data)]
for fpd in flagged_post_data:
if fpd['payout'] >0:
table += '\n|{}|{}|{}|'.format(fpd['link'],str(fpd['payout'])+" SBD", fpd['category'])
table += '\n --- \n'
table1 = '|Link|Flagger|Category|\n|:-----------|:---------:|:--------|'
for q in sql_list:
table1 += '\n|{}|{}|{}|'.format(q[0], q[1], q[2])
body = build_report_body(table)
body += '\n\n\n{}'.format(table1)
sql = cursor.execute(
"SELECT sum(flag_rshares), sum(payout) FROM (SELECT flag_rshares, payout FROM steemflagrewards WHERE included == 0 AND " \
"flagger IN flaggers)")
q = sql.fetchone()
removed = stm.rshares_to_sbd(float(q[0]))
remain = q[1]
body += "\n --- "
try:
body += get_rewards_chart(abs(removed),abs(remain))
except Exception as e:
print(e)
success_ratio = round((abs(removed)/(abs(remain)+abs(removed))*100),2)
if(success_ratio >= 70):
body +="\n # Mission Accomplished! \n"
body +=" http://img200.imageshack.us/img200/3750/missionaccomplishedl.jpg "
else:
body +="\n # Mission Failed! \n"
body +="https://static.giantbomb.com/uploads/original/0/329/1195180-psd3d036.jpg \n"
body += "Reward removal at: "+str(success_ratio)+" % \n\n"
body += flag_leaderboard()
body += '\n\n\n <hr><div class="pull-left"><a href="https://discordapp.com/invite/fmE7Q9q"></a></div> If you feel you\'ve been wrongly flagged, check out @freezepeach, the flag abuse neutralizer. See the <a href="https://steemit.com/introduceyourself/@freezepeach/freezepeach-the-flag-abuse-neutralizer">intro post</a> for more details, or join the <a href="https://discordapp.com/invite/fmE7Q9q">discord server.</a><hr>'
logging.info('Generated post body')
benlist = []
flags = []
#queries flags exceeding minimum payout
payoutflags = cursor.execute(
'SELECT flagger FROM steemflagrewards WHERE included == 0 AND flagger IN flaggers')
for q in payoutflags.fetchall():
flags.append(str(q).split('\'')[1])#extracts username from tuple
#queries flags below dust threshold
dustflags = cursor.execute(
'SELECT flagger FROM steemflagrewards WHERE (included == 0 AND dust == 1) AND flagger IN flaggers')
for q in dustflags.fetchall():
flags.append(str(q).split('\'')[1])#extracts username from tuple
flaggers = set(flags)
for flagger in flaggers:
benlist.append({'account': flagger, 'weight': int(flags.count(flagger)/len(flags)*9500)})
benlist= sorted(benlist, key=lambda k: k['account'],reverse=False)
rep = stm.post(
'Steem Flag Rewards Report - 8 Flagger Post - {}'.format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")),
body, 'steemflagrewards', tags=['steemflagrewards', 'abuse', 'steem', 'flag','busy'], beneficiaries=benlist,
parse_body=True, self_vote=False, community='busy', app='busy/2.5.6')
cursor.execute('UPDATE steemflagrewards SET included = 1 WHERE flagger in flaggers;')
db.commit()
return construct_authorperm(rep['operations'][0][1])
def fill_embed(embed: discord.Embed, names: list, template: str):
"""
Function to add the contents of a list to a discord embed keeping the message size limit in mind
"""
value = ''
for n in names:
if len(value + template.format(n[0])) < 1024:
value += template.format(n[0])
else:
embed.add_field(name='...', value=value, inline=False)
value = template.format(n[0])
embed.add_field(name='...', value=value, inline=False)
async def approve_follow_on(ctx,link):
"""Checks post body for @steemflagrewards mention and https://steemit.com/ and must be in the flag_comment_review
channel id """
global queueing
dust = False
#obtains mods steem account based on pairing in config file and splits our username from single quotes
approving_mod_steem_acct = 'steemflagrewards'
for item in cfg.Moderators:
if item['DiscordID'] == ctx.author.id:
approving_mod_steem_acct = item['SteemUserName']
await ctx.send("Approving mod's Steem Account identified as "+approving_mod_steem_acct+"!")
print(approving_mod_steem_acct)
if ctx.message.channel.id != cfg.FLAG_APPROVAL_CHANNEL_ID:
await ctx.send('Send commands in the right channel please.')
return
logging.info('Registered command for {} by {}'.format(link, ctx.message.author.name))
comment_perm = link.split('@')[-1]
try:
flaggers_comment = Comment(comment_perm, steem_instance=stm)
except ContentDoesNotExistsException:
await ctx.send('Please look at your link again. Could not find the linked comment.')
return
flagger = Account(flaggers_comment['author'])
sfr = Account(cfg.SFRACCOUNT, steem_instance=stm)
if '@{}'.format(cfg.SFRACCOUNT) not in flaggers_comment['body']:
await ctx.send("Could not find a @%s mention. Please check "
"the comment." % (cfg.SFRACCOUNT))
return
cats = get_abuse_categories(flaggers_comment['body'])
if len(cats) == 0:
await ctx.send('No abuse category found.')
return
await ctx.send('Abuse category acknowledged as {}'.format(', '.join(cats)))
parent_perm = construct_authorperm(flaggers_comment['parent_author'],
flaggers_comment['parent_permlink'])
flagged_post = Comment(parent_perm, steem_instance=stm)
cursor.execute('SELECT * FROM steemflagrewards WHERE comment == ?', (flagged_post.authorperm,))
if flagged_post['author'] == cfg.SFRACCOUNT: # Check if flag is a follow on flag
for i in range(2):
parent_perm = construct_authorperm(flagged_post['parent_author'],
flagged_post['parent_permlink'])
flagged_post = Comment(parent_perm, steem_instance=stm)
follow_on = True
await ctx.send('Follow on flag spotted')
elif cursor.fetchone():
follow_on = True
while True:
parent_perm = construct_authorperm(flagged_post['parent_author'],
flagged_post['parent_permlink'])
flagged_post = Comment(parent_perm, steem_instance=stm)
if cursor.execute('SELECT post FROM steemflagrewards WHERE post == ?',
(flagged_post.authorperm,)).fetchall():
break
else:
follow_on = False
cursor.execute('SELECT post FROM steemflagrewards WHERE post == ?', (flagged_post.authorperm,))
if cursor.fetchall():
await ctx.send(
'There has already been some flagging happenin\' on that post/comment. Please consider using the follow on flag feature if you don\'t make a good comment.')
follow_on = True
logging.info(f'Flagged post: {flagged_post.authorperm}')
weight = 0
for v in flagged_post['active_votes']:
if int(v['rshares']) < 0 and v['voter'] == flagger['name']:
await ctx.send('Downvote confirmed')
sfrdvote = v
if stm.rshares_to_sbd(abs(int(v['rshares']))) < 0.0195: #SFR current minimum flag threshold for upvotes
dust = True
follow_on_ROI = 0.1
new_flag_ROI = 0.2
first_flag_ROI = 0.25
ROI = 1.15
if follow_on is True:
ROI += follow_on_ROI
elif follow_on is False:
ROI += new_flag_ROI
else:
await ctx.send('Something went very wrong. I\'m sorry about the inconvenience.')
if not cursor.execute('SELECT flagger FROM steemflagrewards WHERE flagger == ?;', (flagger.name,)):
ROI += first_flag_ROI
if queueing:
voting_power = cfg.MIN_VP * 100
else:
voting_power = sfr.vp * 100
vote_pct = stm.rshares_to_vote_pct(int(abs(int(v['rshares'])) * ROI), # ROI for the flaggers
steem_power=sfr.sp,
voting_power=voting_power)
min_vote_pct = stm.rshares_to_vote_pct(0.0245 / stm.get_sbd_per_rshares(),
steem_power=sfr.sp,
voting_power=voting_power)
weight = max(round((vote_pct / 10000) * 100), round((min_vote_pct / 10000) * 100))
if dust is not True:
if sfr.get_vote(flaggers_comment):
await ctx.send('Already voted on this!')
cursor.execute('SELECT * FROM steemflagrewards WHERE comment == ?', (flaggers_comment.authorperm,))
if cursor.fetchall():
return
else:
insert_mention(approving_mod_steem_acct,cats,dust,flagger, flaggers_comment,flagged_post, sfrdvote, weight, queueing)
db.commit()
return
elif not weight:
await ctx.send('Apparently, the post wasn\'t flagged!')
return
if not queueing or queue_bypass == True:
logging.info('Attempting to vote now.')
comment_age = flaggers_comment.time_elapsed()
if comment_age < datetime.timedelta(minutes=15):
sleeptime = (datetime.timedelta(minutes=15) - comment_age).total_seconds()
await ctx.send('Comment is younger than 15 mins - sleeping for %.1f mins.' % (sleeptime/60))
logging.info('Comment is younger than 15 mins - sleeping for %.1f mins.' % (sleeptime/60))
await asyncio.sleep(sleeptime)
flaggers_comment.upvote(weight=weight, voter=sfr.name)
await asyncio.sleep(cfg.STEEM_MIN_VOTE_INTERVAL)
await ctx.send('Upvoted.')
insert_mention(approving_mod_steem_acct,cats,dust,flagger, flaggers_comment,flagged_post, sfrdvote, weight, queueing)
db.commit()
if not follow_on:
await asyncio.sleep(get_wait_time(sfr))
body = get_approval_comment_body(flaggers_comment['author'], cats,dust)
stm.post('', body,
reply_identifier=flaggers_comment['authorperm'],
community='SFR', parse_body=True,
author=sfr.name)
await ctx.send('Commented.')
else:
await ctx.send('Queued upvote for later on.')
insert_mention(approving_mod_steem_acct,cats,dust,flagger, flaggers_comment,flagged_post, sfrdvote, weight, queueing)
db.commit()
q = \
cursor.execute(
'SELECT COUNT(DISTINCT flagger) FROM steemflagrewards WHERE included == 0;').fetchone()[
0]
await ctx.send('Now at {} out of 9 needed flaggers for a report.'.format(q))
if q > 8:
await ctx.send('Hit flagger threshold. Checking last post age.')
last_post_age = (Comment(construct_authorperm(sfr.get_blog_entries()[0]))).time_elapsed()
if last_post_age < datetime.timedelta(hours=8):
await ctx.send("Posted flagger report less than 8 hours ago so holding off on the report")
return
else:
await ctx.send("Last flagger post has been over 8 hours ago so posting report.")
r = report()
msg = 'Sucessfully posted a new flagger report! Check it out! (And upvote it as well :P)\nhttps://steemit.com/{}'.format(
r)
await ctx.send(msg)
postpromo = bot.get_channel(cfg.POST_PROMOTION_CHANNEL_ID)
await postpromo.send(msg)
sfr.claim_reward_balance()
sfr.refresh()
if sfr.vp < cfg.MIN_VP and not queueing:
await ctx.send(
'Hey my mojo is getting low. I should take a break...\nThat\'s why I\'ll go into queue mode now.'.format(
str(round(sfr.get_voting_value_SBD(), 3))))
queueing = True
await queue_voting(ctx, sfr)
else:
if not follow_on:
await asyncio.sleep(get_wait_time(sfr))
body = get_approval_comment_body(flaggers_comment['author'], cats,dust)
stm.post('', body,
reply_identifier=flaggers_comment['authorperm'],
community='SFR', parse_body=True,
author=sfr.name)
await ctx.send('Commented.')
insert_mention(approving_mod_steem_acct,cats,dust,flagger, flaggers_comment,flagged_post, sfrdvote, weight, queueing)
db.commit()
q = \
cursor.execute(
'SELECT COUNT(DISTINCT flagger) FROM steemflagrewards WHERE included == 0;').fetchone()[
0]
await ctx.send('Now at {} out of 9 needed flaggers for a report.'.format(q))
if q > 8:
await ctx.send('Hit flagger threshold. Checking last post age.')
last_post_age = (Comment(cfg.SFRACCOUNT+'/'+sfr.get_blog_entries()[0]['permlink'])).time_elapsed()
if last_post_age < datetime.timedelta(hours=8):
await ctx.send("Posted less than 8 hours ago so holding off on the report")
return
else:
await ctx.send("Last post has been over 8 hours ago so posting report.")
r = report()
msg = 'Sucessfully posted a new report! Check it out! (And upvote it as well :P)\nhttps://steemit.com/{}'.format(
r)
await ctx.send(msg)
postpromo = bot.get_channel(cfg.POST_PROMOTION_CHANNEL_ID)
await postpromo.send(msg)
sfr.claim_reward_balance()
async def queue_voting(ctx, sfr):
"""
Voting on steemflagrewards mentions one after one once the voting power of the account reached 90%. This maintains a rather stable flagging ROI
"""
global queueing
while queueing:
while sfr.vp < cfg.MIN_VP: # For not failing because of unexpected manual votes
await asyncio.sleep(sfr.get_recharge_timedelta(cfg.MIN_VP).total_seconds())
sfr.refresh()
next_queued = cursor.execute(
'SELECT comment, flagger, category, weight, followon FROM steemflagrewards WHERE queue == 1 ORDER BY created ASC LIMIT 1;').fetchone()
if not next_queued:
queueing = False
await ctx.send('No more mentions left in the queue. Going back to instant voting mode.')
return
authorperm, flagger, cats, weight, follow_on = next_queued
comment = Comment(authorperm, steem_instance=stm)
comment_age = comment.time_elapsed()
if comment_age < datetime.timedelta(minutes=15):
sleeptime = (datetime.timedelta(minutes=15) - comment_age).total_seconds()
await ctx.send('Comment is younger than 15 mins - sleeping for %.1f mins.' % (sleeptime/60))
logging.info('Comment is younger than 15 mins - sleeping for %.1f mins.' % (sleeptime/60))
await asyncio.sleep(sleeptime)
try:
if not sfr.get_vote(comment):
comment.upvote(weight, sfr.name)
await asyncio.sleep(cfg.STEEM_MIN_VOTE_INTERVAL) # sleeps to account for STEEM_MIN_VOTE_INTERVAL
else:
await ctx.send('Already voted on this!')
cursor.execute('UPDATE steemflagrewards SET queue = 0 WHERE comment == ?', (authorperm,))
db.commit()
sfr.refresh()
return
except VotingInvalidOnArchivedPost:
await ctx.send(
'Sadly one comment had to be skipped because it got too old.'
'Maybe the author can delete the comment and write a new one?')
cursor.execute('UPDATE steemflagrewards SET queue = 0 WHERE comment == ?', (authorperm,))
db.commit()
continue
except Exception as e:
await ctx.send(f'Something went wrong while upvoting {comment.author}\'s comment. Skipping it.')
logging.exception(e)
cursor.execute('UPDATE steemflagrewards SET queue = 0 WHERE comment == ?', (authorperm,))
db.commit()
continue
await ctx.send(f'Sucessfully voted on mention by {flagger} out of the queue.')
if not follow_on:
await asyncio.sleep(get_wait_time(sfr))
body = get_approval_comment_body(flagger, cats)
stm.post('', body, reply_identifier=authorperm,
community='SFR', parse_body=True,
author=sfr.name)
await ctx.send('Commented on queued mention.')
cursor.execute('UPDATE steemflagrewards SET queue = 0 WHERE comment == ?', (authorperm,))
db.commit()
sfr.refresh()
return
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
bot = Bot(description='SteemFlagRewards Bot', command_prefix='?')
@bot.command()
async def approve(ctx, link):
"""Checks post body for @steemflagrewards mention and https://steemit.com/ and must be in the flag_comment_review
channel id """
global queueing
dust = False
#obtains mods steem account based on pairing in config file and splits our username from single quotes
approving_mod_steem_acct = 'steemflagrewards'
for item in cfg.Moderators:
if item['DiscordID'] == ctx.author.id:
approving_mod_steem_acct = item['SteemUserName']
await ctx.send("Approving mod's Steem Account identified as "+approving_mod_steem_acct+"!")
print(approving_mod_steem_acct)
if ctx.message.channel.id != cfg.FLAG_APPROVAL_CHANNEL_ID:
await ctx.send('Send commands in the right channel please.')
return
logging.info('Registered command for {} by {}'.format(link, ctx.message.author.name))
comment_perm = link.split('@')[-1]
try:
flaggers_comment = Comment(comment_perm, steem_instance=stm)
except ContentDoesNotExistsException:
await ctx.send('Please look at your link again. Could not find the linked comment.')
return
flagger = Account(flaggers_comment['author'])
sfr = Account(cfg.SFRACCOUNT, steem_instance=stm)
if '@{}'.format(cfg.SFRACCOUNT) not in flaggers_comment['body']:
await ctx.send("Could not find a @%s mention. Please check "
"the comment." % (cfg.SFRACCOUNT))
return
cats = get_abuse_categories(flaggers_comment['body'])
if len(cats) == 0:
await ctx.send('No abuse category found.')
return
await ctx.send('Abuse category acknowledged as {}'.format(', '.join(cats)))
parent_perm = construct_authorperm(flaggers_comment['parent_author'],
flaggers_comment['parent_permlink'])
flagged_post = Comment(parent_perm, steem_instance=stm)
cursor.execute('SELECT * FROM steemflagrewards WHERE comment == ?', (flagged_post.authorperm,))
if flagged_post['author'] == cfg.SFRACCOUNT: # Check if flag is a follow on flag
for i in range(2):
parent_perm = construct_authorperm(flagged_post['parent_author'],
flagged_post['parent_permlink'])
flagged_post = Comment(parent_perm, steem_instance=stm)
follow_on = True
await ctx.send('Follow on flag spotted')
elif cursor.fetchone():
follow_on = True
while True:
parent_perm = construct_authorperm(flagged_post['parent_author'],
flagged_post['parent_permlink'])
flagged_post = Comment(parent_perm, steem_instance=stm)
if cursor.execute('SELECT post FROM steemflagrewards WHERE post == ?',
(flagged_post.authorperm,)).fetchall():
break
else:
follow_on = False
cursor.execute('SELECT post FROM steemflagrewards WHERE post == ?', (flagged_post.authorperm,))
if cursor.fetchall():
await ctx.send(
'There has already been some flagging happenin\' on that post/comment. Please consider using the follow on flag feature if you don\'t make a good comment.')
follow_on = True
logging.info(f'Flagged post: {flagged_post.authorperm}')
weight = 0
for v in flagged_post['active_votes']:
if int(v['rshares']) < 0 and v['voter'] == flagger['name']:
await ctx.send('Downvote confirmed')
sfrdvote = v
if stm.rshares_to_sbd(abs(int(v['rshares']))) < 0.0195: #SFR current minimum flag threshold for upvotes
dust = True
follow_on_ROI = 0.1
new_flag_ROI = 0.2
first_flag_ROI = 0.25
ROI = 1.05
if follow_on is True:
ROI += follow_on_ROI
elif follow_on is False:
ROI += new_flag_ROI
else:
await ctx.send('Something went very wrong. I\'m sorry about the inconvenience.')
if not cursor.execute('SELECT flagger FROM steemflagrewards WHERE flagger == ?;', (flagger.name,)):
ROI += first_flag_ROI
if queueing:
voting_power = cfg.MIN_VP * 100
else:
voting_power = sfr.vp * 100
vote_pct = stm.rshares_to_vote_pct(int(abs(int(v['rshares'])) * ROI), # ROI for the flaggers
steem_power=sfr.sp,
voting_power=voting_power)
min_vote_pct = stm.rshares_to_vote_pct(0.0245 / stm.get_sbd_per_rshares(),
steem_power=sfr.sp,
voting_power=voting_power)
weight = max(round((vote_pct / 10000) * 100), round((min_vote_pct / 10000) * 100))
if dust is not True:
if sfr.get_vote(flaggers_comment):
await ctx.send('Already voted on this!')
return
elif not weight:
await ctx.send('Apparently, the post wasn\'t flagged!')
return
if not queueing or queue_bypass == True:
logging.info('Attempting to vote now.')
comment_age = flaggers_comment.time_elapsed()
if comment_age < datetime.timedelta(minutes=15):
sleeptime = (datetime.timedelta(minutes=15) - comment_age).total_seconds()
await ctx.send('Comment is younger than 15 mins - sleeping for %.1f mins.' % (sleeptime/60))
logging.info('Comment is younger than 15 mins - sleeping for %.1f mins.' % (sleeptime/60))
await asyncio.sleep(sleeptime)
flaggers_comment.upvote(weight=weight, voter=sfr.name)
await ctx.send('Upvoted.')
cursor.execute('INSERT INTO steemflagrewards VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (
flagger.name, flaggers_comment.authorperm, flagged_post.authorperm, ', '.join(cats),
flaggers_comment['created'], False,
stm.rshares_to_sbd(sfrdvote['rshares']), False, weight, follow_on, dust, approving_mod_steem_acct, False))
db.commit()
if not follow_on:
await asyncio.sleep(get_wait_time(sfr))
body = get_approval_comment_body(flaggers_comment['author'], cats,dust)
stm.post('', body,
reply_identifier=flaggers_comment['authorperm'],
community='SFR', parse_body=True,
author=sfr.name)
await ctx.send('Commented.')
else:
await ctx.send('Queued upvote for later on.')
cursor.execute('INSERT INTO steemflagrewards VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (
flagger.name, flaggers_comment.authorperm, flagged_post.authorperm, ', '.join(cats),
flaggers_comment['created'], False,
stm.rshares_to_sbd(sfrdvote['rshares']), queueing, weight, follow_on, dust, approving_mod_steem_acct, False))
db.commit()
q = \
cursor.execute(
'SELECT COUNT(DISTINCT flagger) FROM steemflagrewards WHERE included == 0;').fetchone()[
0]
await ctx.send('Now at {} out of 9 needed flaggers for a report.'.format(q))
if q > 8:
await ctx.send('Hit flagger threshold. Checking last post age.')
last_post_age = (Comment(construct_authorperm(sfr.get_blog_entries()[0]))).time_elapsed()
if last_post_age < datetime.timedelta(hours=8):
await ctx.send("Posted flagger report less than 8 hours ago so holding off on the report")
return
else:
await ctx.send("Last flagger post has been over 8 hours ago so posting report.")
r = report()
msg = 'Sucessfully posted a new flagger report! Check it out! (And upvote it as well :P)\nhttps://steemit.com/{}'.format(
r)
await ctx.send(msg)
postpromo = bot.get_channel(cfg.POST_PROMOTION_CHANNEL_ID)
await postpromo.send(msg)
sfr.claim_reward_balance()
sfr.refresh()
if sfr.vp < cfg.MIN_VP and not queueing:
await ctx.send(
'Hey my mojo is getting low. I should take a break...\nThat\'s why I\'ll go into queue mode now.'.format(
str(round(sfr.get_voting_value_SBD(), 3))))
queueing = True
await queue_voting(ctx, sfr)
else:
if not follow_on:
await asyncio.sleep(get_wait_time(sfr))
body = get_approval_comment_body(flaggers_comment['author'], cats,dust)
stm.post('', body,
reply_identifier=flaggers_comment['authorperm'],
community='SFR', parse_body=True,
author=sfr.name)
await ctx.send('Commented.')
cursor.execute('INSERT INTO steemflagrewards VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (
flagger.name, flaggers_comment.authorperm, flagged_post.authorperm, ', '.join(cats),
flaggers_comment['created'], False,
stm.rshares_to_sbd(sfrdvote['rshares']), False, weight, follow_on, dust, approving_mod_steem_acct, False))
db.commit()
q = \
cursor.execute(
'SELECT COUNT(DISTINCT flagger) FROM steemflagrewards WHERE included == 0;').fetchone()[
0]
await ctx.send('Now at {} out of 9 needed flaggers for a report.'.format(q))
if q > 8:
await ctx.send('Hit flagger threshold. Checking last post age.')
last_post_age = (Comment(cfg.SFRACCOUNT+'/'+sfr.get_blog_entries()[0]['permlink'])).time_elapsed()
if last_post_age < datetime.timedelta(hours=8):
await ctx.send("Posted less than 8 hours ago so holding off on the report")
return
else:
await ctx.send("Last post has been over 8 hours ago so posting report.")
r = report()
msg = 'Sucessfully posted a new report! Check it out! (And upvote it as well :P)\nhttps://steemit.com/{}'.format(
r)
await ctx.send(msg)
postpromo = bot.get_channel(cfg.POST_PROMOTION_CHANNEL_ID)
await postpromo.send(msg)
sfr.claim_reward_balance()
@bot.command()
async def approve_follow_ons(ctx,link):
""" Finds and approves follow on flags for given flag mention comment link"""
comment_perm = link.split('@')[-1]
comment = Comment(comment_perm)
for c in comment.get_replies():
await approve_follow_on(ctx,c.identifier)
await ctx.send('Finished Approving Follow Ons')
return
@bot.command()
async def queue(ctx):
queue = cursor.execute(
'SELECT comment, post FROM steemflagrewards WHERE queue == 1 ORDER BY created ASC;').fetchall()
if not queue:
await ctx.send('No mention in the queue')
return
sfr = Account(cfg.SFRACCOUNT, steem_instance=stm)
queue_embed = discord.Embed(title='@steemflagrewards voting queue',
description=f'Next vote will happen in {sfr.get_recharge_timedelta(cfg.MIN_VP) // 60}.',
color=discord.Color.red())
for mention in queue:
queue_embed.add_field(name=f'Number {queue.index(mention) + 1} in the queue',
value=f'[{mention[0]}](https://steemit.com/{mention[1]}/#{mention[0]})')
await ctx.send(embed=queue_embed)
@bot.command()
async def clear_queue(ctx):
"""
Clears entire voting queue
"""
cursor.execute('UPDATE steemflagrewards SET queue = 0 WHERE queue == 1')
db.commit()
await ctx.send('Queue has been successfully cleared!')
return
@bot.command()
async def unqueue(ctx,permlink):
"""
Removes post from queue by given permlink.
"""
cursor.execute('UPDATE steemflagrewards SET queue = 0 WHERE comment == ?',('@'+permlink,))
db.commit()
await ctx.send('@'+permlink+' successfully removed from queue!')
return
@bot.command()
async def queue_toggle(ctx):
"""
Toggles bypass for queuing mechanism. If queue_bypass already set to TRUE, will set back to FALSE and vice versa.
"""
global queue_bypass
if queue_bypass == False:
queue_bypass = True
await ctx.send('Enabled queue override.')
else:
queue_bypass = False
await ctx.send('Disabled queue override')
return
@bot.command()
async def sdl(ctx, cmd: str, *mode: str):
"""
Manage the list of the steemit defence league accounts with this command. Use it with ?sdl and one of the following
"""
logging.info(f'{ctx.author.name} send sdl command with {cmd} ... {mode}')
if cmd == 'add':
if ctx.author.id not in cfg.SDL_LIST_EDITORS:
await ctx.send('You do not have permissions to edit the SDL list.')
return
if not mode:
await ctx.send('Please provide at least one account name.')
return
for i in mode:
if '@' in i:
i = i.split('@')[-1]
try: