champ 133 Report post Posted April 20 Hi all! We all know that certain users in this community tend to spam other discord servers with their ads, which sometimes can be rather annoying. I wish sometimes I had created this bot when I was running my server. Either way, I created a simple python bot that will prevent users from advertising on your server. It is fairly simple and doesn't involve any sort of complex logic. Feel free to modify it as needed, to make it even more challenging for bots, you could perhaps include AI into creating responses (for instance set up chatgpt api calls), which I'm not going to cover today. Introduction The Discord Anti-Advertisement Bot is designed to prevent users from posting advertisements on a Discord server. The bot monitors messages and deletes any content that it identifies as advertising. Additionally, the bot sends a challenge to new members to verify that they are not bots. Features Detects and deletes advertisement messages. Bans users who exceed the maximum number of advertisement violations. Sends a challenge to new members to verify they are not bots. Automatically assigns a "Bots" role to bots when they join the server. Supports customizable command prefix and challenge questions. Bot Permissions To function correctly, the bot requires the following permissions: Read Messages: To monitor messages in the server. Send Messages: To notify users about their violations and send challenge messages. Manage Messages: To delete advertisement messages. Ban Members: To ban users who exceed the maximum number of violations. Kick Members: To kick users who fail the new member challenge. Manage Roles: To assign roles to bots when they join the server. Configuration 1. Create a new bot To create a new bot, follow these steps: Go to the Discord Developer Portal and sign in with your Discord account. Click "New Application" in the top right corner and enter a name for your application. Navigate to the "Bot" tab on the left sidebar and click "Add Bot." Under the "Token" section, click "Copy" to copy the bot token. 2. Set up the code Clone the bot's repository or download the source code, and make sure you have Python installed. git clone https://github.com/bsgeorgi/discord-anti-ad-bot.git Optionally, you can create a virtual environment and execute your code from there: python -m venv venv venv/Scripts/activate Install the required dependencies using the following command: pip install -r requirements.txt 3. Configure the bot Modify config.py file in the same directory as your bot's code. Replace TOKEN with the token you copied in step 1. You can customize the following settings: TOKEN: The bot token. VIOLATIONS_FILE: The JSON file used to store user violations. MAX_VIOLATIONS: The maximum number of advertisement violations before a user is banned. ALLOWED_DOMAINS: A list of domains that will not trigger the bot's advertising detection. challenges: A list of challenge questions for new members. Each question is a tuple containing a string question and a list of acceptable string answers. 4. Start the bot Run the bot with the following command: python bot.py 5. Invite the bot to your server To invite the bot to your server, follow these steps: Go to the Discord Developer Portal and sign in with your Discord account. Click on your application, then navigate to the "OAuth2" tab on the left sidebar. In the "Scopes" section, select "bot." In the "Bot Permissions" section, select the permissions mentioned earlier in this guide. Copy the generated URL from the "Scopes" section and paste it into a new browser tab. Choose the server where you want to add the bot and click "Authorize." Now, your bot should be a member of your server and will start monitoring messages and performing its tasks. Usage Commands The bot currently has one built-in command: !hello: The bot responds with "Hello!". To use this command, type the command in a text channel in your Discord server. New Member Verification When a new member joins the server, the bot will send them a direct message with a challenge question. The new member must answer the question correctly within 30 seconds. If they answer incorrectly or don't respond within the time limit, they will be kicked from the server. They can rejoin and try again. Advertisement Detection and Handling The bot will continuously monitor messages in the server. If it detects a message containing an advertisement, it will delete the message and notify the sender about their violation. If the user reaches the maximum number of violations (configured in config.py), they will be banned from the server. Customization You can further customize the bot by modifying the code or adding new commands. To add new commands, follow the instructions provided earlier in this conversation. To modify the advertisement detection patterns, edit the patterns.txt file in the bot's directory. Advertisement Patterns I will not go into too much detail when it comes to creating regex patterns, please feel free to do your own research. However, I will explain a couple of patterns from the patterns.txt file. In the provided examples, there are two regular expressions: (?:come\s+)?(play|try|join|check\sout|check) my (new|awesome|amazing|incredible) (game|app|server) This regular expression is composed of several components: (?:come\s+)?: The (?: ... ) is a non-capturing group. It allows you to apply quantifiers to part of your regex without capturing the matched text. In this case, the ? quantifier means the group can occur 0 or 1 times. \s+ represents one or more whitespace characters. So, this part of the regex matches an optional "come" followed by at least one whitespace character. (play|try|join|check\sout|check): This is a capturing group, and the | symbol is an "or" operator, meaning any of the alternatives inside the group can be matched. In this case, the regex will match "play," "try," "join," "check out," or "check." my: Matches the literal string "my." (new|awesome|amazing|incredible): Another capturing group, this time matching any of the adjectives: "new," "awesome," "amazing," or "incredible." (game|app|server): The final capturing group matches one of the following words: "game," "app," or "server." https?://(www\.)?discord\.(?:gg|com/invite)/[^\s]+ This regex is designed to match Discord invite links: https?://: Matches the literal string "http://" or "https://" (the ? makes the "s" optional). (www\.)?: Matches an optional "www." string, with the ? making it optional. discord\.: Matches the literal string "discord." (the backslash is used to escape the dot, as it has a special meaning in regex). (?:gg|com/invite): A non-capturing group that matches either "gg" or "com/invite". /: Matches the literal forward slash character. [^\s]+: The square brackets [] denote a character class, and the ^ symbol inside the brackets negates the class. So, [^\s] means any character that is not a whitespace character. The + quantifier means one or more occurrences of the non-whitespace character. These regular expressions are used in the bot to detect specific patterns related to advertising and can be customized by modifying the patterns.txt file in the bot's directory. Good luck and hope this helps! 1 2 Quote Share this post Link to post Share on other sites
champ 133 Report post Posted April 20 Food for thought: we can create a “report message” command and then upon approval programmatically extract regex pattern from string and append it to our patterns.txt If many enough people are interested, then I can try to implement it. Quote Share this post Link to post Share on other sites
Mdrst 18 Report post Posted April 21 Nice usage of regular expressions A long time ago, bots could private message users inside a discord channel and people would use this as an advertisement method. Does that still happen? I imagine the bot presented wouldn't do too much in those cases... Quote "Beware of bugs in the above code; I have only proved it correct, not tried it." - Donald E. Knuth Share this post Link to post Share on other sites
champ 133 Report post Posted April 21 You can use role permissions so that users inside your discord server with an unassigned role are unable to see a list of other users and then assign the necessary permissions only once their account has been validated. This way, bots will not be able to privately message your players Quote Share this post Link to post Share on other sites
Rogue 16 Report post Posted April 27 Interesting way of handling the issue, good job. Quote Share this post Link to post Share on other sites
V3ct0r 2,033 Report post Posted May 1 Hello @champ, I think it is a very useful development (unfortunately in our community). Thank you! Quote Some useful links / Полезные ссылки Tips for making a topic in 'Questions & Help' / Рекомендации по созданию тем в разделе "Помощь" Server Advertising Section Rules / Правила раздела "Реклама серверов" Available e-mail domains for registration / Допустимые e-mail домены для регистрации User groups / Группы пользователей User ranks / Звания пользователей "Broken" pictures on the forum / "Битые" изображения на форуме Beware of scammers! / Осторожно, мошенники! My developments / Мои разработки Mods for client and server / Моды для клиента и сервера PKOdev.NET website for Tales of Pirates Server / PKOdev.NET веб-обвязка для сервера Пиратии I do not provide any help in private messages and outside the forum. Use 'Questions & Help' section please. Thank you for understanding! Я не оказываю какую-либо помощь в личных сообщениях и вне форума. Пожалуйста, используйте раздел "Пиратия: Помощь". Благодарю за понимание! Share this post Link to post Share on other sites
nyarum12 58 Report post Posted May 20 (edited) Very weird especial in situation where we have very "old" game and every people by my thoughts must support everyone The discord we have for UDIO project has special channel for that and this is beatiful way to handle it instead of block everyone Edited May 20 by nyarum12 Quote Share this post Link to post Share on other sites
champ 133 Report post Posted May 21 10 hours ago, nyarum12 said: Very weird especial in situation where we have very "old" game and every people by my thoughts must support everyone The discord we have for UDIO project has special channel for that and this is beatiful way to handle it instead of block everyone I’m not forcing anybody to use this. When I ran my server, I had hundreds of advertisements sent accords my channels from other servers’ owners on a daily basis. Quote Share this post Link to post Share on other sites
nyarum12 58 Report post Posted May 21 8 часов назад, champ сказал: I’m not forcing anybody to use this. When I ran my server, I had hundreds of advertisements sent accords my channels from other servers’ owners on a daily basis. Yeah sure it just my opinion Quote Share this post Link to post Share on other sites
V3ct0r 2,033 Report post Posted May 21 Hello @nyarum12, Nowadays many of the projects are headed to money making (have commercial basis) and they are not interested to "support everyone" or, in other words, support their competitors, other projects. There is a struggle for attention and the number of players. For such projects @champ's development may be useful and handy. Quote Some useful links / Полезные ссылки Tips for making a topic in 'Questions & Help' / Рекомендации по созданию тем в разделе "Помощь" Server Advertising Section Rules / Правила раздела "Реклама серверов" Available e-mail domains for registration / Допустимые e-mail домены для регистрации User groups / Группы пользователей User ranks / Звания пользователей "Broken" pictures on the forum / "Битые" изображения на форуме Beware of scammers! / Осторожно, мошенники! My developments / Мои разработки Mods for client and server / Моды для клиента и сервера PKOdev.NET website for Tales of Pirates Server / PKOdev.NET веб-обвязка для сервера Пиратии I do not provide any help in private messages and outside the forum. Use 'Questions & Help' section please. Thank you for understanding! Я не оказываю какую-либо помощь в личных сообщениях и вне форума. Пожалуйста, используйте раздел "Пиратия: Помощь". Благодарю за понимание! Share this post Link to post Share on other sites