import pywikibot
import re
import os
import pymysql
site = pywikibot.Site('zh', 'wiktionary')
site.login()
host = os.environ['MYSQL_HOST']
user = os.environ['MYSQL_USERNAME']
password = os.environ['MYSQL_PASSWORD']
conn = pymysql.connect(
    host=host,
    user=user,
    password=password,
    charset="utf8"
)
with conn.cursor() as cur:
    cur.execute('use zhwiktionary_p')
    cur.execute("""
        SELECT page_title
        FROM page
        WHERE page_title LIKE "%་"
            AND page_namespace = 0
        ORDER BY page_title ASC
    """)
    res = cur.fetchall()
text = """* [https://paws-public.wmflabs.org/paws/user/Xiplus/notebooks/zhwikt%20article%20title%20ends%20with%20%22%E0%BC%8B%22.ipynb 來源]

{| class="wikitable sortable"
!頁面 !! 目標"""
for row in res:
    title = row[0].decode()
    text += "\n|-\n"
    text += "|[["+title+"]] || [["+title[:-1]+"]]"
text += "\n|}"
page = pywikibot.Page(site, "Wiktionary:沙盒")
page.text = '{{Sandbox}}\n\n' + text
page.save(summary="產生以音界號結尾的列表", minor=False)
WARNING: API error badtoken: Invalid CSRF token.
Sleeping for 9.7 seconds, 2019-07-06 15:01:42
Page [[wiktionary:zh:Wiktionary:沙盒]] saved