首页 > 代码库 > 聊天机器人

聊天机器人

最近研究微信公众平台,搭建了一个微信聊天机器人,调用小黄鸡的公众接口,实现在线和小黄鸡聊天的功能。

接口调用不是很麻烦,不过是php版本,所以研究了一下C#的功能模块,

Winfrom版

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Threading;namespace 小贱鸡{    public partial class Form1 : Form    {        private static string cookie = null;        private string msg = "";        private Thread th2 = null;        private Thread th3 = null;        private bool changed = false;        public Form1()        {            InitializeComponent();            simsimi.SetAllowUnsafeHeaderParsing20();            Thread th = new Thread(new ThreadStart(Cookie_Thread));            th2 = new Thread(new ThreadStart(Hi_Thread));            th3 = new Thread(new ThreadStart(PowerOn_Thread));            th.Start();            th2.Start();            th3.Start();         }        private void button1_Click(object sender, EventArgs e)        {            if (textBox1.Text != "")            {                changed = true;                msg = textBox1.Text;                textBox1.Text = "";                richTextBox1.Text += String.Format("Me:{0}\n", msg);                changed = false;            }        }         private static void Cookie_Thread()        {            cookie = simsimi.GetCookie();        }        private void PowerOn_Thread()        {            while (cookie == null)            {                this.Invoke(new Action(Update_PowerText), null);                Thread.Sleep(1500);            }             this.Invoke(new Action(Update_PowerFinalText), null);        }        private void Update_PowerText()        {            richTextBox1.Text += "正在开鸡中。。。\n";        }        private void Update_PowerFinalText()        {            richTextBox1.Text += "唔,终于开鸡了。\n小贱鸡:你好,我是小贱鸡。o(∩_∩)o\n";        }        private void Hi_Thread()        {            while (true)            {                while (changed)                {                    this.Invoke(new Action(Update_Text), null);                    break;                }            }        }        private void Update_Text()        {            richTextBox1.Text += String.Format("小贱鸡:{0}\n", simsimi.Hi_Simsimi(msg,cookie));        }        private void textBox1_KeyUp(object sender, KeyEventArgs e)       {            if (e.KeyValue =http://www.mamicode.com/= 13)            {                if (textBox1.Text != "")                {                    changed = true;                    msg = textBox1.Text;                    textBox1.Text = "";                    richTextBox1.Text += String.Format("Me:{0}\n", msg);                    changed = false;                }                      }        }        private void richTextBox1_TextChanged(object sender, EventArgs e)        {            //设定光标所在位置             this.richTextBox1.SelectionStart = richTextBox1.TextLength-1;            //滚动到当前光标处             this.richTextBox1.ScrollToCaret();        }     }}
Code

应用的类代码:应用接口用小黄鸡那边传回来的是一个json形式的内容,所以应用到json的解析问题,我应用的是网上通用的方法Newtonsoft.Json,可以从网上下载对应的DLL

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net;using System.IO;using System.IO.Compression;using System.Reflection;using Newtonsoft.Json;using Newtonsoft.Json.Linq; namespace 小贱鸡{    class simsimi    {        /// <summary>        /// Cookie        /// </summary>        /// <returns></returns>        public static string GetCookie()        {            string Cookiesstr = null;            CookieCollection cookies = new CookieCollection();            HttpWebRequest request = null;            request = (HttpWebRequest)WebRequest.Create("http://www.simsimi.com/talk.htm");            request.CookieContainer = new CookieContainer();            request.CookieContainer.Add(cookies);            //Get the response from the server and save the cookies from the request..            HttpWebResponse response = (HttpWebResponse)request.GetResponse();            Cookiesstr = request.CookieContainer.GetCookieHeader(request.RequestUri);            return Cookiesstr;        }         public static string Hi_Simsimi(string que, string cookies)        {            string ans = "我们换个话题吧";            string url = String.Format("http://www.simsimi.com/func/reqN?lc=ch&ft=0.0&req={0}&fl=http%3A%2F%2Fwww.simsimi.com%2Ftalk.htm", que);            HttpWebRequest hi_request = null;            try            {                hi_request = (HttpWebRequest)WebRequest.Create(url);                hi_request.Method = "GET";                hi_request.KeepAlive = true;                hi_request.ServicePoint.Expect100Continue = false;                hi_request.AllowWriteStreamBuffering = false;                //终端信息                hi_request.Accept = "application/json,text/javascript,*/*;q=0.01";                hi_request.Headers.Add("Accept-Language", "zh-cn");                hi_request.Headers.Add("Accept-Encoding", "gzip,deflate");                hi_request.Headers.Add("Cookie", cookies + ";simsimi_uid=1;");                hi_request.Referer = "http://www.simsimi.com/talk.htm";                hi_request.UserAgent = "Mozilla/4.0(compatible;MSIE 7.0;Windows NT 6.1;Trident/5.0;SLCC2;.NET CLR 2.0.50727;.NET CLR 3.5.30729;.NET CLR 3.0.30729;.NET4.0C;.NET4.0E)";                hi_request.ContentType = "application/json;charset=utf-8";                hi_request.AllowAutoRedirect = false;                HttpWebResponse hi_response = (HttpWebResponse)hi_request.GetResponse();                StreamReader sr = new StreamReader(hi_response.GetResponseStream(), Encoding.UTF8);                ans = sr.ReadToEnd();                if (ans != "{}")                {                    JObject jo = JObject.Parse(ans);                    string[] ArrayList = jo.Properties().Select(item => item.Value.ToString()).ToArray();                    if (ArrayList[0] == "200")                    {                        ans = ArrayList[6];                    }                    else                    {                        ans = "没有听懂,可以再说一遍吗?";                    }                }                hi_request.Abort();                hi_response.Close();            }            catch (System.Exception e)            {                Console.WriteLine(e.ToString());                //return e.ToString();                return "不好意思死鸡了⊙︿⊙重启下程序吧~";            }            return ans;        }               public static bool SetAllowUnsafeHeaderParsing20()        {            //Get the assembly that contains the internal class            Assembly aNetAssembly = Assembly.GetAssembly(typeof(System.Net.Configuration.SettingsSection));            if (aNetAssembly != null)            {                //Use the assembly in order to get the internal type for the internal class                Type aSettingsType = aNetAssembly.GetType("System.Net.Configuration.SettingsSectionInternal");                if (aSettingsType != null)                {                    //Use the internal static property to get an instance of the internal settings class.                    //If the static instance isn‘t created allready the property will create it for us.                    object anInstance = aSettingsType.InvokeMember("Section",                      BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { });                    if (anInstance != null)                    {                        //Locate the private bool field that tells the framework is unsafe header parsing should be allowed or not                        FieldInfo aUseUnsafeHeaderParsing = aSettingsType.GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic | BindingFlags.Instance);                        if (aUseUnsafeHeaderParsing != null)                        {                            aUseUnsafeHeaderParsing.SetValue(anInstance, true);                            return true;                        }                    }                }            }            return false;        }    }}
Code

 

聊天机器人