-
Notifications
You must be signed in to change notification settings - Fork 10
/
main.py
74 lines (61 loc) · 2.12 KB
/
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
import sys
import os
import argparse
from PyPtt import PTT
version = '1.0.1'
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--user', help='ptt username')
parser.add_argument('-p', '--pswd', help='ptt password')
parser.add_argument('-P', '--pswd-path', help='ptt password file')
args = parser.parse_args()
def get_username():
return os.environ.get('USERNAME') or args.user
def get_password():
pswd = os.environ.get('PASSWORD') or args.pswd
if not pswd and args.pswd_path:
path = os.path.abspath(args.pswd_path)
try:
with open(path, 'r') as f:
pswd = f.read()
except FileNotFoundError:
sys.stderr.write('File not found: ' + path + '\n')
sys.exit(87)
except IsADirectoryError:
sys.stderr.write('File is a directory: ' + path + '\n')
sys.exit(87)
except PermissionError:
sys.stderr.write('Permission denied: ' + path + '\n')
sys.exit(87)
except:
sys.stderr.write('Failed to read password from file: ' + path + '\n')
sys.exit(255)
return pswd
def ptt_login(username, password):
ptt_bot = PTT.API(log_level=PTT.log.level.SILENT)
try:
ptt_bot.login(username, password, kick_other_login=True)
print('Login succeeded.')
return 0
except (PTT.exceptions.WrongIDorPassword, PTT.exceptions.WrongPassword):
sys.stderr.write('Wrong password.\n')
return 87
except PTT.exceptions.NoSuchUser:
sys.stderr.write('No such user.\n')
return 87
except PTT.exceptions.LoginTooOften:
sys.stderr.write('Too much login.\n')
return 1
except:
sys.stderr.write('Login failed for unknown reason.\n')
return 255
def main():
username = get_username()
password = get_password()
if not username or not password:
sys.stderr.write('Missing username or password.\n')
sys.exit(87)
print('Start ptt login bot v' + version + '.')
exit_code = ptt_login(username, password)
sys.exit(exit_code)
if __name__ == '__main__':
main()