プログラミング素人のはてなブログ

プログラミングも電気回路も専門外の技術屋の末端が勉強したことや作品をアウトプットするブログ。コードに間違いなど見つけられたら、気軽にコメントください。 C#、Python3、ラズパイなど。

Twitterへの自動投稿

Twitter APIを利用して、定期的にTweetするものを作りました。
f:id:s51517765:20170622223753j:plain

以前の記事の発展。
s51517765.hatenadiary.jp

CoreTweetの基本機能はこの辺を参考に。
blog.ch3cooh.jp

テキストファイルからStreamreaderで読み込んで、ランダムにTweetします。

private void timer1_Tick でタイマー設定。
(プログラミング初心者にありがちな失敗は Thread.Sleepメソッドを使ってしまうこと。Windowsのグルグルが出てきて何もできなくなってしまいます。)
private void AutoTweet() がTweetの本体。
private void buttonPause_Click が自動投稿の停止。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CoreTweet;
using System.Diagnostics;
using System.IO;
using CoreTweet.Streaming;

namespace twitter
{
    public partial class Form1 : Form
    { 
       public Boolean AutoTweet_bool = false;
       public int Set;    //Next Tweet time
       public int interval;     //Tweet Interval

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {             
     
            var tokens = Tokens.Create("******", "******", A_Token, A_TokenSecret);        

 	//Auto Tweet Interval
            comboBoxInterval.Items.Add("15");
            comboBoxInterval.Items.Add("30");
            comboBoxInterval.Items.Add("59");
            comboBoxInterval.Text = "59";
        }

        private void button_AutoTweet_Click(object sender, EventArgs e)
        {
            interval = int.Parse(comboBoxInterval.Text);
            button_AutoTweet.Enabled = false;
            buttonPause.Enabled = true;
            AutoTweet_bool = true;
    
            if (interval > 59)
            {
                interval = 59;
                comboBoxInterval.Text = "59";
            }

            DateTime Now = DateTime.Now;
            timer1.Start();                 // タイマー起動
            Set = Now.Minute + interval;

            if (Set > 59)
            {
                Set = Set - 60;
            }

            AutoTweet(); //初回Tweet
        }

        private void timer1_Tick(object sender, EventArgs e)   //タイマー
        {
            if (AutoTweet_bool == true)
            {
                DateTime Now = DateTime.Now;
                if (Now.Minute == Set)
                {
                    Set = Now.Minute + interval;
           if (Set > 59)
                 {
                    Set = Set - 60;
                 }
                   
                        AutoTweet();
                }
            }
        }

       private void AutoTweet()
        {
            int ListCount=0;
    
                string AutoTweetText = "";
                System.IO.StreamReader sr = new System.IO.StreamReader(@"C:\Users\***\List.txt", System.Text.Encoding.UTF8);                //ファイルを絶対参照で指定したいときは先頭に@を使う
                int LineCount = 1;
            button_AutoTweet.Enabled = false;
            while (sr.Peek() >= 0)
            {
                //一行ずつ読み込む
                AutoTweetText = sr.ReadLine();
                ListCount++;
       
            }
            sr.Close();

            System.Random r = new System.Random();
            int rand = r.Next(1,ListCount);  //LineCount
  
               System.IO.StreamReader sr2 = new System.IO.StreamReader(@"C:\Users\***\List.txt", System.Text.Encoding.UTF8);

            while (sr2.Peek() >= 0)
                {
                    //一行ずつ読み込む
                    AutoTweetText = sr2.ReadLine();
                    LineCount++;
                    if (LineCount == rand)
                    {
                        break;
                    }
                }
                //閉じる
                sr2.Close();
       
           try
             {
                    var tokens = Tokens.Create("******", "******", A_Token, A_TokenSecret);
                if (checkBoxDebug.Checked == false)
                {
                    tokens.Statuses.Update(status => AutoTweetText); //tweet
                }
                else
                {
                    MessageBox.Show(AutoTweetText);
                }
                    DateTime dt = DateTime.Now;
                    textBoxStatus.AppendText(dt.ToString("HH:mm:ss") +" "+AutoTweetText.Substring(0,17) +"… Complete!" + Environment.NewLine);
             }

           catch
            {
                    DateTime dt = DateTime.Now;
                    textBoxStatus.AppendText(dt.ToString("HH:mm:ss") + "Auto Tweet Error!" + Environment.NewLine);
            }
        }

        private void buttonPause_Click(object sender, EventArgs e)
        {
            buttonPause.Enabled = false;
            button_AutoTweet.Enabled = true;
            AutoTweet_bool = false;
        }
    }
}