Jamie Tu
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- breaks: true # False means NOT to render line breaks as hard line breaks. --- Wikidata 入門筆記 4 - 撰寫 bot ============================== ###### tags: `Wikidata` {%hackmd pPCm34WnTpyby2g957L4Gg %} :::info [(點我用書本模式瀏覽)](https://hackmd.io/@jd3main/H1TpO43CX/) ::: :::warning 施工中 ::: ## 概述 這篇會簡單介紹如何用 Python 撰寫 Wikidata bot。 以下介紹兩個套件:**[Pywikibot](https://github.com/wikimedia/pywikibot)** 和 **[WikidataIntegrator](https://github.com/SuLab/WikidataIntegrator)** #### Pywikibot Pywikibot 是官方提供的套件,功能相當完整,可以滿足大多數的需求,尤其當你需要和其他維基網站(例如維基百科)互動時,這會是你最好的選擇。 ##### 優點: * 官方支援 * 方便製作跨不同維基網站的 bot * Lazy 取得 entity 的資料 ##### 缺點: * 目前不支援 Lexical Data * 教學文件新舊混雜 * GitHub 上只是鏡像,主要 repo 在 Gerrit,開發者要貢獻的學習成本比較高 #### WikidataIntegrator 和 Pywikibot 不同,WikidataIntegrator 並不是對於 MediaWiki 的完整包裝,而是強調整合透過 Query Service 提供結構化的查詢能力。 ##### 優點: * 不用親自寫 SPARQL 就能做基本的結構化查詢 ##### 缺點: * 沒有支援完整的 MediaWiki API * 部分功能沒有跟上新版本的 API * 缺乏教學文件 * 不利於編輯已存在的 entity * 資料結構包裝得不好用 * 容易不小心打亂已經存在的 claims ## pywikibot > 本文撰寫時的版本:6.6.1 ### 實用資源 * [Tutorial](https://www.wikidata.org/wiki/Wikidata:Pywikibot_-_Python_3_Tutorial) * [API Reference](https://doc.wikimedia.org/pywikibot/master/api_ref/index.html) ### 安裝 ``` pip install pywikibot ``` ### 登入 例如正在撰寫名叫 `nice_bot` 的機器人 資料夾可能長這樣 ``` nice_bot/ |-- __init__.py |-- user-config.py ``` 帳號必須在 `user-config.py` 裡給定(很遺憾的似乎不能從 API 直接傳) `user-config.py` 的內容如下: ```python= family = 'wikidata' mylang = 'wikidata' usernames['wikidata']['test'] = 'nice_bot' ``` 如果要登入 www.wikidata.org 則改成: ```python=3 usernames['wikidata']['wikidata'] = 'nice_bot' ``` 在 `__init__.py` 裡可以這樣寫: ```python= from pywikibot.data.api import LoginManager psw = input("password: ") site = pywikibot.Site("test", "wikidata") login_manager = LoginManager(password=psw, site=site) success = login_manager.login() print(f"success: {success}") ``` 要注意的是 `LoginManager` 必須使用 `pywikibot.data.api` 底下的,`pywikibot.login.LoginManager` 是沒辦法直接使用的。 > 雖然 `LoginManager` 可以傳 user 參數 > 依然需要在 `user-config.py` 當中設定 `usernames` 才能使用 ### 基本使用 [Wikidata:Creating_a_bot](https://www.wikidata.org/wiki/Wikidata:Creating_a_bot) 上面這個頁面有非常多的範例,包含了大多數的使用需求 但值得一題的是,你**不需要**像裡面的範例一樣寫成 ```python= site = pywikibot.Site("test", "wikidata") repo = site.data_repository() ``` 因為這裡 site 和 repo 是完全相等的 請參考下面的使用範例 #### 取得資料 ```python= from pywikibot import Site, ItemPage site = Site('wikidata', 'wikidata') item = ItemPage(site, 'Q65555605') data = item.get() print(data) ``` ### 疑難排解 #### `badtoken: Invalid CSRF token` 有可能是 bot 運行太久導致 token 過期 如果必須長時間執行,可以試試 ++[這個方法](https://phabricator.wikimedia.org/T261050#6421048)++ ## WikidataIntegrator > 本文撰寫時的版本:0.9.12 ### 安裝 ``` pip install wikidataintegrator ``` ### 文件 在我撰寫這篇時,沒找到可直接在網站上瀏覽的文件,因此提供手動 build 文件的方式 #### 步驟 1. 更新 pip ``` python -m pip install -U pip ``` 2. 安裝 [Sphinx](https://www.sphinx-doc.org/en/master/) ``` pip install Sphinx ``` 3. 從 [GitHub](https://github.com/SuLab/WikidataIntegrator) 下載,或找到套件安裝的路徑 4. 找到 `docs/source/conf.py`,在裡面加入這幾行 ```python= def skip(app, what, name, obj, would_skip, options): if name == "__init__": return False return would_skip def setup(app): app.connect("autodoc-skip-member", skip) ``` 這是為了讓 `__init__()` 也被納入文件 5. 在 `docs` 資料夾開啟 termina,輸入: ``` make html ``` > 如果還有顯示缺少套件,應該大多可以直接用 pip 安裝 6. 打開 `docs/build/html/index.html` 就可以瀏覽文件了 :::warning 文件中可能有不少壞掉的地方,通常是因為 docstring 中多出或缺少空白行,如有需要可以手動修正或是找更好的文件生成軟體來處理 :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully