3
4

More than 3 years have passed since last update.

wikipediaガチャBotをつくってみた

Posted at

はじめに

ノンプログラマですが,自分でも何かつくってみたくてTwitterBotをつくりました.
初学者がBot作成する際のご参考になれば幸いです.

できたもの

wikipediaに登録されている単語から,2つの単語をランダムに取得してTweetするBotです.
https://twitter.com/Sosaku_Tango
スクリーンショット 2020-01-05 0.19.56.png

つくりかた

まず完成したコードがこちらです.

import tweepy, random
import schedule
import time

# 取得した各keyを代入
CK=""
CS=""
AT=""
AS=""

# インスタンス作成
auth = tweepy.OAuthHandler(CK, CS)
auth.set_access_token(AT, AS)
api = tweepy.API(auth)

#ダウンロードしたwikipedia単語リストファイルから2つの単語をツイート
def bot():
    wiki_titles = open("jawiki-latest-all-titles-in-ns0.txt", "r")
    line = wiki_titles.readlines()
    random_word = random.sample(line, 1)
    first_word = ''.join(random_word)
    random_word = random.sample(line, 1)
    second_word = ''.join(random_word)

    api.update_status('1.' + first_word + '2.' + second_word + '\nで創作できますか?出来上がりを楽しみにしています. #創作単語 ')

#定期的な実行
def main():
    schedule.every().day.at("10:00").do(bot)
    while True:
        schedule.run_pending()
        time.sleep(1)
main()
  1. Tweepyを使用したTwitterBotの基本的な作成方法は,こちらを参考にしました.
    https://qiita.com/tsc343/items/e51f412480ea8bf5619a

  2. Wikipediaの単語データ(.txt)はこちらからダウンロードしました.
    https://dumps.wikimedia.org/jawiki/

  3. txtファイルからランダムに行を抽出するコードはこちらを参考にしました.
    http://tksmd.hatenablog.com/entry/20090122/p1

  4. 定期的な自動実行はこちらを参考にしました.
    https://qiita.com/Kai-Suzuki/items/0c5c0e5cbdb4075fe482

  5. 完成です.お疲れ様でした.

しょかん

最近まで手動で毎日実行していたのですが,忘れることがたびたびあったので自動実行のコードを入れました.
それを機にQiitaで初投稿してみた次第です.
フォローもいいねも0なので誰にも認識されていないのですが,興味があれば一度見てもらえると嬉しいです.
なにかお気付きの点があればコメントいただけると幸いです.

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4