一个VK机器人,一个C#和一个橙色

为了好玩,我继续用“智能”房屋进行实验,我决定在VK中添加一个组来控制其某些特征。 在本文中,我们指定任务:我们将尝试使用C#语言编写一个简单的bot,该机器人将代表VK中的社区做出响应,并考虑如何在arm32上快速启动它(在我的情况下,是橙色pi零)。



关于部署的思考
还有许多其他选项(例如,放置运行时),这是其中之一

因此,将其放在架子上。

在VK中创建应用程序
这是详细的文档
  1. 要创建机器人,请转到此处
    单击“创建应用程序”,然后选择“独立应用程序”。
  2. 现在我们转到管理,并在“应用程序ID”选项卡中记住其ID。 这将对我们进一步有用。


我们获得了与团体合作的象征
  1. 我们只需将请求插入浏览器行即可发送请求:
    https://oauth.vk.com/authorize?client_id=YOURAPPID&group_ids=YOURGROUPID6&display=page&scope=messages,wall,manage&response_type=token&v=5.92 

    其中YOURAPPID是我们在上一个剧透中找到的应用程序ID,而YOURGROUPID ID是您的社区。
  2. 我们授予访问该应用程序的权限
  3. 我们得到这个答案
     https://oauth.vk.com/blank.html#expires_in=0&access_token_YOURGROUPID=YOURTOKEN 

    令牌是拉丁字母和数字的很长的组合


获得令牌更容易
  1. 去社区管理


建立一个社区进行长期民意调查
  1. 我们转到社区的“管理”选项卡。
  2. Api用法及其中的LongPoll Api
  3. 事件类型(事件),在其中我们标记为必需,对于测试,我会标记所有内容。


我们转到主要部分:

启动您最喜欢的ide,在net core上创建一个控制台应用程序



添加VkNet

扰流板
不幸的是,在Wiki上,文档有些过时了。 创建本指南的原因之一。
但是这里有很大的支持


使用我们的令牌登录:

 var api = new VkApi(); api.Authorize(new ApiAuthParams(){AccessToken =MyAppToken }); 

而且我们将无休止地收到更新

 var s = api.Groups.GetLongPollServer(MyGroupId); while (true) { var poll = api.Groups.GetBotsLongPollHistory( new BotsLongPollHistoryParams() {Server = s.Server, Ts = s.Ts, Key = s.Key, Wait = 1}); } 

让我们检查一下是否有东西来

 if(poll?.Updates== null) continue; 

对于收到的所有数据,我们将查找是否有任何消息,如果是,则打印其内容

  foreach (var a in poll.Updates) { if (a.Type == GroupUpdateType.MessageNew) { Console.WriteLine(a.Message.Body); } } 

我们将用相同的文字回答用户

  api.Messages.Send(new MessagesSendParams() { UserId = a.Message.UserId, Message = a.Message.Body }); 


收到的代码
 class Program { public static string MyAppToken => "f6bf5e26*************************************************************"; public static ulong MyGroupId => 10******; static void Main(string[] args) { var api = new VkApi(); api.Authorize(new ApiAuthParams(){AccessToken =MyAppToken }); var s = api.Groups.GetLongPollServer(MyGroupId); while (true) { try { var poll = api.Groups.GetBotsLongPollHistory( new BotsLongPollHistoryParams() {Server = s.Server, Ts = s.Ts, Key = s.Key, Wait = 1}); if(poll?.Updates== null) continue; foreach (var a in poll.Updates) { if (a.Type == GroupUpdateType.MessageNew) { Console.WriteLine(a.Message.Body); api.Messages.Send(new MessagesSendParams() { UserId = a.Message.UserId, Message = a.Message.Body }); } } } } } catch (LongPollException exception) { if (exception is LongPollOutdateException outdateException) server.Ts = outdateException.Ts; else { s = api.Groups.GetLongPollServer(MyGroupId); } } catch (Exception e) { Console.WriteLine(e.Message); } } } 


让我们为董事会收集收到的代码

 dotnet publish . -r linux-arm 

并在板上拖动所需的目录



我们通过ssh运行

 chmod +x ConsoleApp1 ./ConsoleApp1 

结果
传送讯息



我们在控制台中收到消息



我们得到答案



对话对话


Source: https://habr.com/ru/post/zh-CN431090/


All Articles