using System;
|
using System.Collections.Generic;
|
using System.IO;
|
using System.Text;
|
using WeChatIn;
|
using WeChatIn.Entity;
|
using WeChatIn.Messages;
|
using ZTImage.Log;
|
|
namespace RichCreator.Server.Providers
|
{
|
/// <summary>
|
/// 微信提供
|
/// </summary>
|
public class WechatProvider
|
{
|
private WechatProvider()
|
{ }
|
|
|
|
/// <summary>
|
/// 微信客户端
|
/// </summary>
|
private WeChatClient client;
|
private bool isLogin=false;
|
private WeChatUser me;
|
|
/// <summary>
|
/// 向微信发送消息
|
/// </summary>
|
/// <param name="user">微信备注名</param>
|
/// <param name="content">内容</param>
|
public void SendMessage(string user, string content)
|
{
|
if (!isLogin)
|
{
|
return;
|
}
|
WeChatUser wuser = this.client.GetUserByRemarkName(user);
|
if (user == null)
|
{
|
return;
|
}
|
this.SendMessage(wuser.UserName, content);
|
}
|
|
/// <summary>
|
/// 登陆微信
|
/// </summary>
|
public void LoginWechat()
|
{
|
LoginWechat(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "qrcode.png"));
|
}
|
|
/// <summary>
|
/// 登陆微信
|
/// </summary>
|
/// <param name="qrcodeSaveDir"></param>
|
public void LoginWechat(string qrcodeSaveDir)
|
{
|
this.client = new WeChatClient();
|
|
this.client.OnLogined = (c) =>
|
{
|
Trace.Info("login success,concat:" + c.Contacts.Count + ",nick:" + c.Me.NickName + ",username:" + c.Me.UserName);
|
isLogin = true;
|
this.client.OnReceive = OnReceiveMessage;
|
me = this.client.GetUserByRemarkName("xiaozhuan");
|
};
|
|
this.client.Start(qrcodeSaveDir);
|
}
|
|
/// <summary>
|
/// 收到消息回调
|
/// </summary>
|
/// <param name="msg"></param>
|
private void OnReceiveMessage(Message msg)
|
{
|
if (me == null)
|
{
|
return;
|
}
|
|
if (msg.From == client.Me.UserName)
|
{
|
return;
|
}
|
|
if (msg.MessageType==MessageType.Text&&msg.From == me.UserName)
|
{
|
//来自小砖,执行命令
|
ExecuteCommand(msg.Content);
|
return;
|
}
|
|
string content = string.Empty;
|
string showName = client.GetUserByUserName(msg.From).ShowName;
|
if (msg.MessageType == MessageType.Text)
|
{
|
content = $"收到“{showName}”的消息,{msg.Content}";
|
}
|
else
|
{
|
content = $"收到“{showName}”的消息,消息类型:{msg.MessageType.ToString()}";
|
}
|
client.SendMessage(me.UserName, content);
|
}
|
|
/// <summary>
|
/// 执行命令
|
/// </summary>
|
/// <param name="command"></param>
|
private void ExecuteCommand(string command)
|
{
|
Trace.Info($"命令:{command}");
|
}
|
|
#region singleton
|
private static WechatProvider instance;
|
private static object lockHelper = new object();
|
public static WechatProvider Instance
|
{
|
get
|
{
|
if (instance == null)
|
{
|
lock (lockHelper)
|
{
|
if (instance == null)
|
{
|
instance = new WechatProvider();
|
}
|
}
|
}
|
return instance;
|
}
|
}
|
|
#endregion
|
}
|
}
|