URI: 
       wikipediagame - annna - Annna the nice friendly bot.
  HTML git clone git://bitreich.org/annna/ git://enlrupgkhuxnvlhsf6lc3fziv5h2hhfrinws65d7roiv6bfj7d652fid.onion/annna/
   DIR Log
   DIR Files
   DIR Refs
   DIR Tags
   DIR README
       ---
       wikipediagame (5100B)
       ---
            1 #!/usr/bin/env python3.14
            2 # coding=utf-8
            3 #
            4 # Idea from: https://github.com/izabera/izabot/blob/master/cus_lib.py#L89
            5 #
            6 
            7 import os
            8 import sys
            9 import getopt
           10 import wikipedia as w
           11 import json
           12 import random
           13 import time
           14 from datetime import timedelta
           15 from difflib import SequenceMatcher
           16 
           17 def usage(app):
           18     app = os.path.basename(app)
           19     print("usage: %s [-h] cmd" % (app), file=sys.stderr)
           20     sys.exit(1)
           21 
           22 def concealtitle(s, title):
           23     splittitle = title.replace(",", " ").replace("-", " ")
           24     for titlepart in splittitle.split():
           25         s = s.replace(titlepart, "*" * len(titlepart))
           26     return s
           27 
           28 def geturi(wpage):
           29     wuri = wpage.url
           30     return wuri.replace("https://en.wikipedia.org/wiki", "gophers://bitreich.org/0/pedia/txt")
           31 
           32 def endgame(hintpath, titlepath):
           33     if os.path.exists(hintpath):
           34         os.remove(hintpath)
           35     if os.path.exists(titlepath):
           36         os.remove(titlepath)
           37 
           38 def main(args):
           39     try:
           40         opts, largs = getopt.getopt(args[1:], "h")
           41     except getopt.GetoptError as err:
           42         print(str(err))
           43         usage(args[0])
           44 
           45     basepath = "%s/wikipediagame/%s-%s-%s-%s" % \
           46         (os.getenv("ANNNA_MODBASE", "/home/annna/bin/modules"),
           47          os.getenv("IRC_SERVER", "server"),
           48          os.getenv("IRC_PORT", "port"),
           49          os.getenv("IRC_USER", "user"),
           50          os.getenv("IRC_CHANNEL", "channel"))
           51     printsummary = 0
           52     newtitle = 0
           53     title = None
           54 
           55     w.set_user_agent("WikiGameBot/0.2 (https://bitreich.org; 20h@r-36.net)")
           56     w.set_rate_limiting(True, timedelta(seconds=1))
           57     time.sleep(1)
           58 
           59     for o, a in opts:
           60         if o == "-h":
           61             usage(args[0])
           62         else:
           63             assert False, "unhandled option"
           64 
           65     if len(largs) < 1:
           66         usage(args[0])
           67 
           68     os.makedirs(basepath, exist_ok=True)
           69     titlepath = "%s/lasttitle" % (basepath)
           70     hintpath = "%s/hintsize" % (basepath)
           71 
           72     cmd = largs[0]
           73     if cmd == "init":
           74         if len(largs) > 1:
           75             searchresults = w.search(largs[1])
           76             while len(searchresults) > 0:
           77                 title = random.choice(searchresults)
           78                 try:
           79                     summary = w.summary(title)
           80                     break
           81                 except w.exceptions.DisambiguationError:
           82                     searchresults.remove(title)
           83                     continue
           84 
           85         if title == None:
           86             summary = None
           87             while summary == None:
           88                 title = str(w.random())
           89                 try:
           90                     summary = w.summary(title)
           91                 except (w.exceptions.DisambiguationError, w.exceptions.PageError):
           92                     continue
           93 
           94         if os.path.exists(hintpath):
           95             os.remove(hintpath)
           96         if os.path.exists(titlepath):
           97             os.remove(titlepath)
           98         newtitle = 1
           99         printsummary = 1
          100     else:
          101         if os.path.exists(titlepath):
          102             titlefd = open(titlepath, "r")
          103             title = str(json.load(titlefd))
          104             titlefd.close()
          105         else:
          106             title = ""
          107 
          108     if len(title) == 0:
          109         print("There is no game started. Please run init.")
          110         return 0
          111 
          112     if newtitle == 1:
          113         titlefd = open(titlepath, "w+")
          114         json.dump(title, titlefd)
          115         titlefd.close()
          116 
          117     if cmd == "summary":
          118         printsummary = 1
          119 
          120     if printsummary == 1:
          121         if summary == None:
          122             summary = w.summary(title)
          123         summary = summary.replace("\n", " ")
          124         print(concealtitle(summary, title))
          125 
          126     if os.path.exists(hintpath):
          127         hintfd = open(hintpath, "r")
          128         try:
          129             hintsize = int(json.load(hintfd))
          130         except json.decoder.JSONDecodeError:
          131             hintsize = 0
          132         hintfd.close()
          133     else:
          134         hintsize = 0
          135 
          136     if cmd == "hint":
          137         hintsize += 3
          138         hint = title[:hintsize] \
          139             + "".join(["*" if c != ' ' else ' ' for c in title[hintsize:]])
          140         print("Hint: %s" % (hint))
          141 
          142         hintfd = open(hintpath, "w+")
          143         json.dump(hintsize, hintfd)
          144         hintfd.close()
          145 
          146     if cmd == "more":
          147         wpage = w.page(title)
          148         images = [item for item in wpage.images if item.find('/commons/')]
          149         if len(images) > 0 and random.random() < 0.5:
          150             print(random.choice(images))
          151         else:
          152             paragraphs = wpage.content.split('\n')
          153             paragraph = random.choice([item for item in paragraphs if len(item) > 5 and item[0] != '='])
          154             print(concealtitle(paragraph, title))
          155 
          156     if cmd == "guess":
          157         if len(largs) < 2:
          158             usage(args[0])
          159         trytext = largs[1]
          160         if title.strip().lower() == trytext.strip().lower():
          161             print("Congrats! You have found the right title! :: %s" % (geturi(w.page(title))))
          162             endgame(hintpath, titlepath)
          163         else:
          164             print("Sorry, wrong guess. (%.0f%% correct)" % \
          165                                 (SequenceMatcher(None, title.strip().lower(), trytext.strip().lower()).ratio() * 100))
          166 
          167     if cmd == "giveup":
          168         print("The correct title was: %s" % (geturi(w.page(title))))
          169         endgame(hintpath, titlepath)
          170 
          171     return 0
          172 
          173 if __name__ == "__main__":
          174     sys.exit(main(sys.argv))
          175