-
Notifications
You must be signed in to change notification settings - Fork 8
/
steemvoter
executable file
·208 lines (175 loc) · 6.77 KB
/
steemvoter
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
#!/usr/bin/env python3
import argparse
from collections import OrderedDict
import logging
import threading
import time
import traceback
import sys
import humanfriendly
from steemvote.config import Config, ConfigError
from steemvote.db import DBVersionError
from steemvote.models import Priority
from steemvote.monitor import Monitor
from steemvote.voter import Voter
# Default interval for voting on eligible comments.
DEFAULT_VOTE_INTERVAL = 10 # 10 seconds.
def print_config(voter):
"""Print info regarding voter's configuration."""
header = '---------- Steemvote Configuration ----------'
footer = '-' * len(header)
# Pad lengths so that all values are aligned.
format_str = '{key:{pad_length}}: {value}'.format
print(header)
config = voter.config
if config.get('log_file'):
print('Log file: %s\n' % config.get('log_file'))
voting_config = OrderedDict()
voting_config['Minimum post age'] = humanfriendly.format_timespan(voter.min_post_age)
voting_config['Maximum post age'] = humanfriendly.format_timespan(voter.max_post_age)
for priority_level in Priority:
key = 'Minimum voting power (%s priority)' % priority_level.value
value = voter.priority_voting_powers[priority_level]
voting_config[key] = '{voting_power:.{decimals}%}'.format(voting_power=value,
decimals=len(str(value)) - 3)
if voter.blacklisted_authors:
voting_config['Blacklisted authors'] = str(voter.blacklisted_authors)
voting_config['Blacklisted categories'] = str(voter.blacklisted_categories)
longest_key_length = max([len(i) for i in voting_config.keys()])
for k, v in voting_config.items():
print(format_str(key=k, value=v, pad_length=longest_key_length))
# Output author configuration.
# Split author lists into lines of 5 items each.
authors_config = OrderedDict()
authors = sorted(config.authors, key = lambda i: i.name)
for priority_level in Priority:
names = [i.name for i in [author for author in authors if author.priority == priority_level]]
lists = []
for i in range(0, len(names), 5):
lists.append(names[i:i+5])
authors_config['%s priority' % priority_level.value.capitalize()] = lists
print('')
print('Authors:')
for k, v in authors_config.items():
if not len(v):
continue
print(' - %s:' % k)
for names in v:
print('\t{}'.format(str(names)[1:-1]))
# Output delegate configuration.
# Split delegate lists into lines of 5 items each.
delegates_config = OrderedDict()
delegates = sorted(config.delegates, key = lambda i: i.name)
for priority_level in Priority:
names = [i.name for i in [delegate for delegate in delegates if delegate.priority == priority_level]]
lists = []
for i in range(0, len(names), 5):
lists.append(names[i:i+5])
delegates_config['%s priority' % priority_level.value.capitalize()] = lists
print('')
print('Delegates:')
for k, v in delegates_config.items():
if not len(v):
continue
print(' - %s:' % k)
for names in v:
print('\t{}'.format(str(names)[1:-1]))
print(footer)
def run_steemvoter(config):
logger = logging.getLogger('steemvote')
try:
voter = Voter(config)
monitor = Monitor(voter)
vote_interval = config.get_seconds('vote_interval', DEFAULT_VOTE_INTERVAL)
# Vote interval cannot be less than one second.
if vote_interval < 1:
raise ConfigError('The minimum value for "vote_interval" is 1 second')
except ConfigError as e:
print('Config Error: %s' % str(e))
return
sys.exit(1)
except DBVersionError as e:
print('Database Error: %s' % str(e))
return
sys.exit(1)
print_config(voter)
last_vote = time.time()
logger.info('Starting steemvoter\n')
voter.connect_to_steem()
voter.update()
monitor.start()
while 1:
now = time.time()
try:
# voter will update via RPC once every interval.
voter.update()
if now - last_vote > vote_interval:
last_vote = now
voter.vote_for_comments()
else:
time.sleep(1)
except KeyboardInterrupt:
logger.debug('Received keyboard interrupt. Quitting.')
break
except Exception as e:
logger.error(str(e))
logger.error(''.join(traceback.format_tb(sys.exc_info()[2])))
monitor.stop()
voter.close()
def run_steemvoter_qt(config):
# Putting these imports here allows the command-line to be used
# without PyQt4 installed.
try:
from PyQt4.QtGui import QApplication
except ImportError:
print('PyQt4 is not installed. Please install it or use the -t option.')
print('On Ubuntu, it can be installed with: `sudo apt-get install python3-pyqt4`')
from steemvote.gui import SteemvoteWindow
app = QApplication(sys.argv)
try:
window = SteemvoteWindow(config, app)
except ConfigError as e:
print('Config Error: %s' % str(e))
sys.exit(1)
except DBVersionError as e:
print('Database Error: %s' % str(e))
sys.exit(1)
sys.exit(window.main())
def main():
# Command-line arguments.
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config', type=str, default='', help='Path to config file')
parser.add_argument('-t', '--terminal', action='store_true', default=False, help='Do not launch a window')
parser.add_argument('-w', '--wif', type=str, help='Private key')
parser.add_argument('--logfile', type=str, default='', help='File to write log messages to')
args = parser.parse_args()
# Silence the piston logger.
logger = logging.getLogger()
logger.setLevel(logging.CRITICAL)
# Initialize logging.
logger = logging.getLogger('steemvote')
formatter = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] %(message)s')
ch = logging.StreamHandler()
ch.setFormatter(formatter)
logger.addHandler(ch)
logger.setLevel(logging.DEBUG)
# Initialize config.
config = Config()
config.load(args.config)
if args.logfile:
config.set('log_file', args.logfile)
if args.wif:
config.set('vote_key', args.wif)
# Write log messages to a file, if given.
log_file = config.get('log_file', '')
if log_file:
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.INFO)
logger.addHandler(file_handler)
if args.terminal:
return run_steemvoter(config)
else:
return run_steemvoter_qt(config)
if __name__ == '__main__':
main()