дать роль, когда пользователь добавляет реакцию Discord.net

Я пытаюсь добавить отзыв (удар вверх + удар вниз), который будет встроен в сообщение EmbedBuilder. Если пользователь поднимает палец вверх, затем применяет к нему роль «хорошо», если он показывает отрицательный палец, применяет роль «плохо», а также при удалении его типа реакции (thump..up / dawn) удаляется его роль (win / терять).

message_txt_Embed - это встроенное сообщение, которое будет отправлено.

Private Async Function onMsg(message As SocketMessage) As Task
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If message.Source = MessageSource.Bot Then
        'ignore bot repeat message message
Else

   If message.Content = message_txt_Embed.text Then

            Dim msg As String = message.Content
            Dim embed As New EmbedBuilder With {
      .Title = msg,
      .Description = "No Description",
      .Color = New Discord.Color(255, 0, 0)
       }
            Await message.Channel.SendMessageAsync("", False, embed)


            '''''' what i try to add reaction for user's who add reaction

            Dim guild As SocketGuild = (CType(message.Channel, SocketGuildChannel)).Guild
            Dim emote As IEmote = guild.Emotes.First(Function(e) e.Name = ":thumbsup:")
            Await guild.Users.AddReactionAsync(emote)

            ''''''
        End If

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
End If

Как это работает, когда я меняю message_txt_Embed.text например на "test", а затем запускаю бота. Если я набрал "test" [как message_txt_Embed.text], то создайте embed msg.

Моя точка зрения: как я могу применить роль для пользователя, когда добавлена ​​реакция (thump..up / dawn), а также удалить роль, если он удалил свою реакцию.


person Bego.    schedule 03.05.2019    source источник
comment
Не могли бы вы прояснить, что вы имеете в виду: как это работает, когда я меняю message_txt_Embed.text, например, для тестирования, а затем запускаю бота. Если я набрал test [as message_txt_Embed.text], то создайте embed msg.   -  person Anu6is    schedule 03.05.2019
comment
@ Anu6is в порядке, пусть будет, когда запуск бота отправит встроенное сообщение для определенного канала. Id 45 ....., и если пользователь добавит реакцию (удар вверх) добавит ему роль как победа / И если он удалил (удар вверх) реакция, затем снимите с него роль, если обнаружите, что выиграет   -  person Bego.    schedule 03.05.2019


Ответы (1)


Во-первых, я хотел бы прояснить некоторые проблемы с помощью примера кода. См. Комментарии ниже

'This function is only called when a message is recieved by the client.
'It is not going to be called when a user adds a reaction to a message.
'As such, no logic should be included in here in relation to reactions.
Private Async Function onMsg(message As SocketMessage) As Task

If message.Source = MessageSource.Bot Then
        'Instead of having an empty bode in your condition, you could use:

        'If Not message.Source = MessageSource.Bot Then 
        '   execute your logic
        'End If     

        'The code above would remove the need for includeing an ELSE section 
        'and no longer require the IF section to be empty
Else
    If message.Content = message_txt_Embed.text Then
        Dim msg As String = message.Content
        Dim embed As New EmbedBuilder With {
            .Title = msg,
            .Description = "No Description",
            .Color = New Discord.Color(255, 0, 0)
       }

       Await message.Channel.SendMessageAsync("", False, embed)

       Dim guild As SocketGuild = (CType(message.Channel, SocketGuildChannel)).Guild

       'If you are trying to get the standard thumbsup emoji this is not going to work
       'SocketGuild#Emotes is a collection of custom emotes that are available in the guild.
       'If this thumbsup is in fact a custom emote you'd access the name withoug the ':'
       Dim emote As IEmote = guild.Emotes.First(Function(e) e.Name = ":thumbsup:")
       Await guild.Users.AddReactionAsync(emote) 'This is not a valid function.
    End If
End If

Решение:
- Создайте список (Of Ulong), который будет использоваться для хранения идентификатора любого сообщения, которое должно иметь роль при добавлении реакции. Это гарантирует, что не будут назначены роли для реагирования на любое сообщение в канале.
- Используйте события ReactionAdded и ReactionRemoved, чтобы отслеживать реакции, добавляемые или удаляемые пользователями.

Вы можете найти документацию по ReactionAdded Event здесь

'Any time a message is created with the purpose of adding reaction roles
'that message id should be added to this list. 
'This example does not include code for populating this list!
Private ReadOnly ReactionMessages As New List(Of ULong)
'Subscribe to the ReactionAdded and ReactionRemoved events (code not included)

Реакция добавлена ​​ - Добавить роль

    Private Async Function ReactionAdded(cache As Cacheable(Of IUserMessage, ULong), channel As ISocketMessageChannel, reaction As SocketReaction) As Task
        If Not reaction.User.IsSpecified Then Return

        'cache.id is the id of the message the user added the reaction to
        'Check if the message the user is reacting to is a valid reaction message
        'If valid, the message id should exist in our ReactionMessages collection
        'Valid reaction messages are the only message that should assign or remove roles
        If ReactionMessages.Contains(cache.Id) Then
            Dim role As IRole = Nothing

            'The unicode string (???? and ????) is used when comparing Discord emojis
            If reaction.Emote.Name.Equals("????") Then
                'Retrieve the "good role" from the guild, using the role id
                role = DirectCast(channel, SocketGuildChannel).Guild.GetRole(123456789)
            ElseIf reaction.Emote.Name.Equals("????") Then
                'Retrieve the "bad role" from the guild, using the role id
                role = DirectCast(channel, SocketGuildChannel).Guild.GetRole(987654321)
            End If

            'Only if the role was found within the guild should we attempt to add it to the user
            If role IsNot Nothing Then Await DirectCast(reaction.User.Value, SocketGuildUser).AddRoleAsync(role)
        End If
    End Function

Реакция удалена - удалить роль

    Private Async Function ReactionRemoved(cache As Cacheable(Of IUserMessage, ULong), channel As ISocketMessageChannel, reaction As SocketReaction) As Task
        If Not reaction.User.IsSpecified Then Return

        'cache.id is the id of the message the user is reacting to
        'Check if the message the user is reacting to is a valid reaction message
        'If valid, the message id should exist in our ReactionMessages collection
        'Valid reaction messages are the only message that should assign or remove roles
        If ReactionMessages.Contains(cache.Id) Then
            Dim role As IRole = Nothing
            Dim user As SocketGuildUser = reaction.User.Value

            'The unicode string (???? and ????) is used when comparing Discord emojis
            If reaction.Emote.Name.Equals("????") Then
                'Retrieve the "good role" from the guild, using the role id
                role = DirectCast(channel, SocketGuildChannel).Guild.GetRole(123456789)
            ElseIf reaction.Emote.Name.Equals("????") Then
                'Retrieve the "bad role" from the guild, using the role id
                role = DirectCast(channel, SocketGuildChannel).Guild.GetRole(987654321)
            End If

            'If the role was found within the guild and the user currently has the role assigned, remove the role from the user
            If role IsNot Nothing AndAlso user.Roles.Any(Function(r) r.Id = role.Id) Then Await user.RemoveRoleAsync(role)
        End If
    End Function
person Anu6is    schedule 03.05.2019
comment
@ Bego, это твой старый код, к которому я добавил комментарии. В этой строке я добавил комментарий This is not a valid function. Как насчет того, чтобы прочитать все предоставленное решение и попытаться понять, о чем говорится. - person Anu6is; 03.05.2019
comment
Конечно, я видел, что это недопустимая функция, и я устал, но я спросил причину после того, как многие из них потерпели неудачу. Я постараюсь изо всех сил, надеюсь, я получу это, чтобы ответить. - person Bego.; 03.05.2019
comment
Теперь это сработало, но это только добавление роли, когда я удаляю свою реакцию, а не удаляю свою роль. это может только добавить - person Bego.; 04.05.2019
comment
Спасибо, все исправил. - person Bego.; 04.05.2019