Fix or silence Pylint issues

This commit is contained in:
Midgard 2020-12-09 15:09:39 +01:00
parent 3d1ef9309f
commit c64658d773
Signed by: midgard
GPG key ID: 511C112F1331BBB4
2 changed files with 31 additions and 20 deletions

View file

@ -4,10 +4,9 @@ import sys
import os import os
from collections import defaultdict from collections import defaultdict
import datetime import datetime
import threading
from time import sleep from time import sleep
import json import json
from typing import Optional, Mapping, Set from typing import Dict, Set
import mattermost import mattermost
import mattermost.ws import mattermost.ws
@ -43,7 +42,8 @@ try:
since_arg_i = sys.argv.index("--since") since_arg_i = sys.argv.index("--since")
except ValueError: except ValueError:
SINCE = datetime.datetime.now(tz=datetime.timezone.utc) SINCE = datetime.datetime.now(tz=datetime.timezone.utc)
print(f"Warning: no start time provided, using now. Use `--since {SINCE.isoformat(timespec='seconds')}` to pin the start time.", file=sys.stderr) print(f"Warning: no start time provided, using now. Use `--since "
f"{SINCE.isoformat(timespec='seconds')}` to pin the start time.", file=sys.stderr)
if since_arg_i: if since_arg_i:
SINCE = datetime.datetime.fromisoformat(sys.argv[since_arg_i + 1]) SINCE = datetime.datetime.fromisoformat(sys.argv[since_arg_i + 1])
@ -75,15 +75,22 @@ else:
assert PASSWORD assert PASSWORD
mm.login(USER, PASSWORD) mm.login(USER, PASSWORD)
# pylint: disable=protected-access # bad library design: can't fix this without extra API request
our_user_id = mm._my_user_id our_user_id = mm._my_user_id
################################## ##################################
# Get channel # Get channel
team_data = first(filter(lambda team: team["name"] == TEAM_NAME, mm.get_teams())) team_data = first(filter(
lambda team: team["name"] == TEAM_NAME,
mm.get_teams()
))
assert team_data, "Team should exist" assert team_data, "Team should exist"
channel_data = first(filter(lambda chan: chan["name"] == CHAN_NAME, mm.get_team_channels(team_data["id"]))) channel_data = first(filter(
lambda chan: chan["name"] == CHAN_NAME,
mm.get_team_channels(team_data["id"])
))
assert channel_data, "Channel should exist" assert channel_data, "Channel should exist"
channel = channel_data["id"] channel = channel_data["id"]
@ -122,6 +129,7 @@ def parse_mm_timestamp(mm_timestamp):
return datetime.datetime.fromtimestamp(mm_timestamp / 1000, datetime.timezone.utc) return datetime.datetime.fromtimestamp(mm_timestamp / 1000, datetime.timezone.utc)
def to_mm_timestamp(dt): def to_mm_timestamp(dt):
# pylint: disable=invalid-name
return int(dt.timestamp() * 1000) return int(dt.timestamp() * 1000)
@ -159,7 +167,7 @@ def emit_change_line(post, awardee_id, awarder_id, prev_score, score):
# awarded[awardee][post_id][verifier]: set of values # awarded[awardee][post_id][verifier]: set of values
awarded: Mapping[str, Mapping[str, Mapping[str, Set[int]]]] = \ awarded: Dict[str, Dict[str, Dict[str, Set[int]]]] = \
defaultdict(lambda: defaultdict(lambda: defaultdict(set))) defaultdict(lambda: defaultdict(lambda: defaultdict(set)))
@ -214,7 +222,8 @@ def get_posts_for_channel(mmapi, channel_id, since, **kwargs):
after = order[-1] after = order[-1]
CONFIRMATION_EMOJI_NAMES = "one,two,three,four,five,six,seven,eight,nine,keycap_ten,asterisk".split(",") CONFIRMATION_EMOJI_NAMES = \
"one,two,three,four,five,six,seven,eight,nine,keycap_ten,asterisk".split(",")
def confirmation_emoji_name(count): def confirmation_emoji_name(count):
if count < 0: if count < 0:
return "exclamation" return "exclamation"
@ -224,13 +233,13 @@ def confirmation_emoji_name(count):
return CONFIRMATION_EMOJI_NAMES[-1] return CONFIRMATION_EMOJI_NAMES[-1]
def persevere(f, backoff=1): def persevere(f, e_type=Exception, backoff=1):
while True: while True:
try: try:
f() f()
return return
except Exception as e: except e_type as exc:
print(e, file=sys.stderr) print(exc, file=sys.stderr)
print(f"Trying again in {backoff} second(s)", file=sys.stderr) print(f"Trying again in {backoff} second(s)", file=sys.stderr)
sleep(backoff) sleep(backoff)
@ -264,10 +273,12 @@ def update_confirmation(post_id):
def remove_reactions_from_post(post): def remove_reactions_from_post(post):
for reaction in post.get("metadata", {}).get("reactions", []): for reaction in post.get("metadata", {}).get("reactions", []):
if reaction["user_id"] == our_user_id: if reaction["user_id"] == our_user_id:
# pylint: disable=cell-var-from-loop # persevere doesn't store lambda
persevere(lambda: remove_reaction(post["id"], reaction["emoji_name"])) persevere(lambda: remove_reaction(post["id"], reaction["emoji_name"]))
def remove_reaction(post_id, emoji_name): def remove_reaction(post_id, emoji_name):
# pylint: disable=protected-access # library recommends this in docs
mm._delete(f"/v4/users/me/posts/{post_id}/reactions/{emoji_name}") mm._delete(f"/v4/users/me/posts/{post_id}/reactions/{emoji_name}")
@ -279,7 +290,7 @@ def handle_backlog(since):
def handle_live(): def handle_live():
def ws_handler(mmws, event_data): def ws_handler(_mmws, event_data):
if event_data["broadcast"]["channel_id"] != channel: if event_data["broadcast"]["channel_id"] != channel:
return return
@ -288,7 +299,7 @@ def handle_live():
elif event_data["event"] == "reaction_removed": elif event_data["event"] == "reaction_removed":
retract_if_appropriate(json.loads(event_data["data"]["reaction"])) retract_if_appropriate(json.loads(event_data["data"]["reaction"]))
ws = mattermost.ws.MMws(ws_handler, mm, f"wss://{SERVER}/api/v4/websocket") _ = mattermost.ws.MMws(ws_handler, mm, f"wss://{SERVER}/api/v4/websocket")
while True: while True:
sleep(60 * 1000) sleep(60 * 1000)
@ -298,7 +309,8 @@ if clean:
remove_reactions_from_post(_post) remove_reactions_from_post(_post)
else: else:
# Note: skipping this step and updating an existing file would be dangerous: you would miss revocations that happened while not listening. # Note: skipping this step and updating an existing file would be dangerous:
# you would miss revocations that happened while not listening.
handle_backlog(SINCE) handle_backlog(SINCE)
if live: if live:

View file

@ -4,19 +4,19 @@ import sys
import re import re
from datetime import datetime from datetime import datetime
from collections import defaultdict from collections import defaultdict
from typing import Mapping, Set from typing import Dict
if sys.stdin.isatty(): if sys.stdin.isatty():
print("Hint: stdin is a terminal, you may want to do `./make_table.py < verifications.log` instead.", file=sys.stderr) print("Hint: stdin is a terminal, "
"you may want to do `./make_table.py < verifications.log` instead.", file=sys.stderr)
# users[awardee][post_id][verifier]: score # users[awardee][post_id][verifier]: score
users: Mapping[str, Mapping[str, Mapping[str, int]]] = \ users: Dict[str, Dict[str, Dict[str, int]]] = \
defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: 0))) defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: 0)))
for line_nr, line in enumerate(sys.stdin, start=1): for line_nr, line in enumerate(sys.stdin, start=1):
line = line.rstrip() line = line.rstrip()
# {awardee} {post['id']} at {post_time}: {awarder} verified with score {score}
m = re.fullmatch(r"([^ ]+) ([^ ]+) at ([^ ]+): ([^ ]+) verified with score ([^ ]+)", line) m = re.fullmatch(r"([^ ]+) ([^ ]+) at ([^ ]+): ([^ ]+) verified with score ([^ ]+)", line)
if m: if m:
awardee = m.group(1) awardee = m.group(1)
@ -28,8 +28,8 @@ for line_nr, line in enumerate(sys.stdin, start=1):
users[awardee][post_id][verifier] = score users[awardee][post_id][verifier] = score
continue continue
# {awardee} {post['id']} at {post_time}: {awarder} updated their verification's score from {prev_score} to {score} m = re.fullmatch(r"([^ ]+) ([^ ]+) at ([^ ]+): ([^ ]+) updated their verification's score "
m = re.fullmatch(r"([^ ]+) ([^ ]+) at ([^ ]+): ([^ ]+) updated their verification's score from ([^ ]+) to ([^ ]+)", line) "from ([^ ]+) to ([^ ]+)", line)
if m: if m:
awardee = m.group(1) awardee = m.group(1)
post_id = m.group(2) post_id = m.group(2)
@ -41,7 +41,6 @@ for line_nr, line in enumerate(sys.stdin, start=1):
users[awardee][post_id][verifier] = score users[awardee][post_id][verifier] = score
continue continue
# {awardee} {post['id']} at {post_time}: {awarder} retracted their verification
m = re.fullmatch(r"([^ ]+) ([^ ]+) at ([^ ]+): ([^ ]+) retracted their verification", line) m = re.fullmatch(r"([^ ]+) ([^ ]+) at ([^ ]+): ([^ ]+) retracted their verification", line)
if m: if m:
awardee = m.group(1) awardee = m.group(1)