├── LICENSE
├── README.md
├── images
├── creating-discord-bot-step-1.png
├── creating-discord-bot-step-2.png
├── creating-discord-bot-step-3.png
├── creating-discord-bot-step-4.png
├── creating-discord-bot-step-5.png
├── creating-discord-bot-step-6.png
├── creating-discord-bot-step-7.png
├── creating-discord-bot-step-8.png
└── creating-discord-bot-step-9.png
├── javascript
├── en
│ ├── README.md
│ ├── saeson1.md
│ ├── saeson2.md
│ ├── saeson3.md
│ ├── saeson4.md
│ ├── saeson5.md
│ ├── saeson6.md
│ ├── saeson7.md
│ └── saeson8.md
└── per
│ ├── README.md
│ ├── saeson1.md
│ ├── saeson2.md
│ ├── saeson3.md
│ ├── saeson4.md
│ ├── saeson5.md
│ ├── saeson6.md
│ ├── saeson7.md
│ └── saeson8.md
└── python
├── en
├── README.md
├── saeson1.md
├── saeson10.md
├── saeson11.md
├── saeson2.md
├── saeson3.md
├── saeson4.md
├── saeson5.md
├── saeson6.md
├── saeson7.md
├── saeson8.md
└── saeson9.md
└── per
├── README.md
├── saeson1.md
├── saeson10.md
├── saeson11.md
├── saeson2.md
├── saeson3.md
├── saeson4.md
├── saeson5.md
├── saeson6.md
├── saeson7.md
├── saeson8.md
└── saeson9.md
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021-2025 Sobhan (Sobhan-SRZA) and Persian-Caesar
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## ⁉ How to Create a Discord Bot?
2 |
3 |

4 |
5 |

6 |

7 |

8 |
9 |

10 |

11 |

12 |

13 |

14 |

15 |

16 |
17 |

18 |
19 |
20 | ---
21 |
22 | ## 🇺🇸 English
23 |
24 | Hello everyone,
25 |
26 | In this project, we will teach you how to create a Discord bot professionally using **JavaScript** and **Python**.
27 |
28 | ### Prerequisites
29 |
30 | Before you begin, make sure you have:
31 |
32 | * Adequate knowledge of [JavaScript](https://eloquentjavascript.net/) or [Python](https://cfm.ehu.es/ricardo/docs/python/Learning_Python.pdf).
33 | * A code editor such as Notepad or [Visual Studio Code](https://code.visualstudio.com/download).
34 | * A [Discord account](https://discord.com/login).
35 | * A [Discord bot application](https://discord.com/developers).
36 |
37 |
38 | Once you have all prerequisites, choose your programming language to start building your Discord bot. 📌
39 |
40 | * [JavaScript](/javascript/en/README.md)
41 | * [Python](/python/en/README.md)
42 |
43 |
44 |
45 | ---
46 |
47 | ## 🇮🇷 فارسی
48 |
49 | سلام و درود بر شما عزیزان،
50 |
51 | در این مقاله قصد داریم نحوه ساخت ربات دیسکورد به صورت حرفهای را با **JavaScript** و **Python** به شما آموزش دهیم.
52 |
53 | ### پیش نیازها
54 |
55 | برای شروع مطمئن شوید که:
56 |
57 | * دانش کافی در [JavaScript](https://eloquentjavascript.net/) یا [Python](https://cfm.ehu.es/ricardo/docs/python/Learning_Python.pdf) دارید.
58 | * یک ویرایشگر کد مانند Notepad یا [Visual Studio Code](https://code.visualstudio.com/download) نصبشده دارید.
59 | * حساب کاربری [Discord](https://discord.com/login) دارید.
60 | * یک اپلیکیشن ربات در [سرویس توسعه دهندگان Discord](https://discord.com/developers) ساختهاید.
61 |
62 |
63 | هنگامی که تمام پیش نیاز ها را دارید، زبان برنامه نویسی خود را انتخاب کنید و آموزش ساخت ربات دیسکورد را شروع کنید. 📌
64 |
65 | * [JavaScript](/javascript/per/README.md)
66 | * [Python](/python/per/README.md)
67 |
68 |
69 |
70 | ---
71 |
72 | # **📫| Contact me in**
73 |
136 |
137 |
138 |
--------------------------------------------------------------------------------
/images/creating-discord-bot-step-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sobhan-SRZA/How-Create-Discord-Bot/30d2ce95a7dc9db16169a7be136520eddf34cc36/images/creating-discord-bot-step-1.png
--------------------------------------------------------------------------------
/images/creating-discord-bot-step-2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sobhan-SRZA/How-Create-Discord-Bot/30d2ce95a7dc9db16169a7be136520eddf34cc36/images/creating-discord-bot-step-2.png
--------------------------------------------------------------------------------
/images/creating-discord-bot-step-3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sobhan-SRZA/How-Create-Discord-Bot/30d2ce95a7dc9db16169a7be136520eddf34cc36/images/creating-discord-bot-step-3.png
--------------------------------------------------------------------------------
/images/creating-discord-bot-step-4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sobhan-SRZA/How-Create-Discord-Bot/30d2ce95a7dc9db16169a7be136520eddf34cc36/images/creating-discord-bot-step-4.png
--------------------------------------------------------------------------------
/images/creating-discord-bot-step-5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sobhan-SRZA/How-Create-Discord-Bot/30d2ce95a7dc9db16169a7be136520eddf34cc36/images/creating-discord-bot-step-5.png
--------------------------------------------------------------------------------
/images/creating-discord-bot-step-6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sobhan-SRZA/How-Create-Discord-Bot/30d2ce95a7dc9db16169a7be136520eddf34cc36/images/creating-discord-bot-step-6.png
--------------------------------------------------------------------------------
/images/creating-discord-bot-step-7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sobhan-SRZA/How-Create-Discord-Bot/30d2ce95a7dc9db16169a7be136520eddf34cc36/images/creating-discord-bot-step-7.png
--------------------------------------------------------------------------------
/images/creating-discord-bot-step-8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sobhan-SRZA/How-Create-Discord-Bot/30d2ce95a7dc9db16169a7be136520eddf34cc36/images/creating-discord-bot-step-8.png
--------------------------------------------------------------------------------
/images/creating-discord-bot-step-9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sobhan-SRZA/How-Create-Discord-Bot/30d2ce95a7dc9db16169a7be136520eddf34cc36/images/creating-discord-bot-step-9.png
--------------------------------------------------------------------------------
/javascript/en/README.md:
--------------------------------------------------------------------------------
1 | # Table of Contents
2 |
3 | ### [**Chapter 1: Introduction and Setting Up the Environment**](./saeson1.md)
4 |
5 | 1. **What is Programming?**
6 |
7 | * Why Discord and Node.js?
8 | * Uses of Discord bots.
9 | 2. **Required Tools**
10 |
11 | * Installing Node.js and npm.
12 | * Introduction to code editors (e.g., VS Code).
13 | * Creating a bot in the Discord Developer Portal.
14 | * Getting the bot token.
15 |
16 | ---
17 |
18 | ### [**Chapter 2: Understanding JavaScript Basics**](./saeson2.md)
19 |
20 | 1. **Variables and Data Types**
21 |
22 | * `let`, `const`, `var`
23 | * Strings, numbers, booleans, arrays, objects.
24 | 2. **Operators and Control Structures**
25 |
26 | * Arithmetic, comparison, and logical operators.
27 | * Conditions (`if/else`, `switch`).
28 | * Loops (`for`, `while`).
29 | 3. **Functions and Modules**
30 |
31 | * Defining functions (regular and arrow functions).
32 | * Function inputs and outputs.
33 | * Introduction to `require` and `module.exports`.
34 |
35 | ---
36 |
37 | ### [**Chapter 3: Introduction to Node.js and npm**](./saeson3.md)
38 |
39 | 1. **What is Node.js?**
40 |
41 | * Running JavaScript outside the browser.
42 | * Event-driven and non-blocking architecture.
43 | 2. **Managing Packages with npm**
44 |
45 | * Installing packages (e.g., `npm install discord.js`).
46 | * Understanding `package.json` and managing dependencies.
47 |
48 | ---
49 |
50 | ### [**Chapter 4: Getting Started with discord.js**](./saeson4.md)
51 |
52 | 1. **Introduction to the discord.js Library**
53 |
54 | * Why use discord.js?
55 | * Basic structure of a Discord bot.
56 | 2. **Creating Your First Bot**
57 |
58 | * Connecting to Discord with `Client` and token.
59 | * The `ready` event and successful login response.
60 | * Responding to user messages (`messageCreate` event).
61 |
62 | ---
63 |
64 | ### [**Chapter 5: Creating Simple Commands**](./saeson5.md)
65 |
66 | 1. **Command Handling**
67 |
68 | * Recognizing command prefixes (e.g., `!ping`).
69 | * Replying to users (`message.reply()`).
70 | 2. **Working with Embeds**
71 |
72 | * Creating stylish messages using `EmbedBuilder`.
73 | * Adding fields, colors, and images.
74 |
75 | ---
76 |
77 | ### [**Chapter 6: More Advanced Concepts**](./saeson6.md)
78 |
79 | 1. **Error Handling**
80 |
81 | * Using `try/catch`.
82 | * Preventing bot crashes.
83 | 2. **Working with Slash Commands**
84 |
85 | * Registering global/server-specific commands.
86 | * Responding to interactions (`interaction.reply()`).
87 | 3. **Storing Data**
88 |
89 | * Intro to simple databases (e.g., JSON files or SQLite).
90 | * Saving settings or user info.
91 |
92 | ---
93 |
94 | ### [**Chapter 7: Deploying and Maintaining the Bot**](./saeson7.md)
95 |
96 | 1. **Deploying Your Bot to a Server**
97 |
98 | * Using free hosting services (like Replit or Railway).
99 | * Running the bot 24/7.
100 | 2. **Optimization and Security**
101 |
102 | * Hiding your token using `.env`.
103 | * Managing resources and memory.
104 |
105 | ---
106 |
107 | ### [**Chapter 8: Practical Projects**](./saeson8.md)
108 |
109 | 1. **Creating a Poll Bot**
110 |
111 | * Using reactions to collect results.
112 | 2. **Music Player Bot**
113 |
114 | * Connecting to a voice channel and playing music.
115 | 3. **User Leveling System (XP System)**
116 |
117 | * Tracking user activity and rewarding engagement.
118 |
119 | ---
120 |
121 | ### **Appendices and Additional Resources**
122 |
123 | * List of useful discord.js commands.
124 | * Links to official [discord.js](https://discord.js.org/#/) documentation.
125 | * Support communities (Discord, Stack Overflow).
126 |
127 | ---
128 |
129 | ### **Key Teaching Tips:**
130 |
131 | * Start each section with simple examples and runnable code.
132 | * Use visuals and screenshots for better guidance.
133 | * Include small exercises after each lesson to reinforce concepts.
134 | * Emphasize debugging and error reading.
--------------------------------------------------------------------------------
/javascript/en/saeson1.md:
--------------------------------------------------------------------------------
1 | ## **Chapter 1: Introduction and Setting Up Your Environment**
2 |
3 | ---
4 |
5 | ### **1.1 What Is Programming?**
6 |
7 | Programming means writing instructions that a computer executes to produce a specific output or behavior.
8 |
9 | * **Why Discord and Node.js?**
10 |
11 | * Discord is a popular platform for building online communities, and bots can add features like automated moderation, mini-games, or smart interactions to your servers.
12 | * **Node.js** is a JavaScript runtime that lets you run your code outside the browser (for example, on a server). It’s ideal for creating Discord bots with the `discord.js` library.
13 |
14 | ---
15 |
16 | ### **1.2 Required Tools**
17 |
18 | Before you begin, make sure you have the following tools installed and ready:
19 |
20 | #### **1.2.1 Installing Node.js and npm**
21 |
22 | 1. Go to the [Node.js website](https://nodejs.org).
23 | 2. Download and install the **LTS** (Long-Term Support) version.
24 | 3. After installation, open your terminal (or Command Prompt) and run:
25 |
26 | ```bash
27 | node -v # This should print your Node.js version (e.g., v18.12.1)
28 | npm -v # This should print your npm version (e.g., 8.19.2)
29 | ```
30 |
31 | #### **1.2.2 Code Editor: VS Code**
32 |
33 | * VS Code is a free, popular code editor. Download and install it from [here](https://code.visualstudio.com).
34 |
35 | #### **1.2.3 Creating Your Bot on Discord**
36 |
37 | 1. Visit the [Discord Developer Portal](https://discord.com/developers/applications).
38 | 2. Click **New Application** and choose a name for your bot.
39 | 3. In the left sidebar, select **Bot**, then click **Add Bot**.
40 | 4. Copy the bot’s **Token** and keep it somewhere safe—it’s like your bot’s password!
41 |
42 | 
43 | 
44 | 
45 | 
46 | 
47 | 
48 | 
49 | 
50 | 
51 |
52 | ---
53 |
54 | ### **1.3 Starting Your First Project**
55 |
56 | 1. Create a new folder for your project (for example, `my-first-bot`).
57 | 2. Open that folder in VS Code.
58 | 3. In the VS Code terminal, initialize a new Node.js project:
59 |
60 | ```bash
61 | npm init -y
62 | ```
63 | 4. Install the `discord.js` library:
64 |
65 | ```bash
66 | npm install discord.js
67 | ```
68 |
69 | ---
70 |
71 | ### **1.4 Testing Your Bot’s Connection to Discord**
72 |
73 | Create a file named `index.js` and paste in the following code:
74 |
75 | ```javascript
76 | const { Client, GatewayIntentBits } = require('discord.js');
77 | const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages] });
78 |
79 | client.on('ready', () => {
80 | console.log(`Bot logged in successfully! Name: ${client.user.tag}`);
81 | });
82 |
83 | client.on('messageCreate', (message) => {
84 | if (message.content === 'سلام') {
85 | message.reply('سلام! چطوری؟');
86 | }
87 | });
88 |
89 | client.login('YOUR_TOKEN_HERE');
90 | ```
91 |
92 | * Replace `'YOUR_TOKEN_HERE'` with your actual bot token.
93 | * Run the bot in your terminal:
94 |
95 | ```bash
96 | node index.js
97 | ```
98 | * If everything is set up correctly, your bot will come online in Discord and reply to “سلام” with “سلام! چطوری؟”.
99 |
100 | ---
101 |
102 | ### **1.5 Hands-On Exercise for Chapter 1**
103 |
104 | 1. Create a new Discord bot and obtain its token.
105 | 2. Write the `index.js` file as shown above and run the bot.
106 | 3. In your Discord server, send the bot the message “سلام” and verify its reply.
107 |
108 | ---
109 |
110 | ### **Key Tips**
111 |
112 | * **Never** share your bot token with anyone!
113 | * If your bot doesn’t go online:
114 |
115 | * Double-check that you pasted the token correctly.
116 | * Ensure your internet connection is active.
117 | * Make sure you’ve invited your bot to your server (use the **OAuth2** link in the Developer Portal).
118 |
119 | In the next chapter, we’ll dive into the fundamental concepts of JavaScript! 🚀
--------------------------------------------------------------------------------
/javascript/en/saeson2.md:
--------------------------------------------------------------------------------
1 | ## **Chapter 2: Getting to Know JavaScript Fundamentals**
2 |
3 | ---
4 |
5 | ### **2.1 Variables and Data Types**
6 |
7 | Variables are like boxes that store data.
8 |
9 | #### **Variable Declarations**
10 |
11 | * **`let`**:
12 | Use for variables whose values **change**.
13 |
14 | ```javascript
15 | let age = 20;
16 | age = 21; // This is allowed
17 | ```
18 |
19 | * **`const`**:
20 | Use for variables whose values are **fixed** (cannot be changed).
21 |
22 | ```javascript
23 | const PI = 3.14;
24 | // PI = 5; // Error! You cannot reassign a const
25 | ```
26 |
27 | * **`var`**:
28 | An older form of declaration that is less commonly used today (because of scoping issues).
29 |
30 | #### **Data Types**
31 |
32 | 1. **String**:
33 | Holds text inside quotes (`""`, `''`, or \`\`\`\`).
34 |
35 | ```javascript
36 | let name = "Alice";
37 | let message = 'Hello!';
38 | ```
39 |
40 | 2. **Number**:
41 | Includes integers and decimals.
42 |
43 | ```javascript
44 | let price = 1000;
45 | let temperature = 23.5;
46 | ```
47 |
48 | 3. **Boolean**:
49 | Only two possible values: `true` or `false`.
50 |
51 | ```javascript
52 | let isOnline = true;
53 | let hasPermission = false;
54 | ```
55 |
56 | 4. **Array**:
57 | A numbered list of values.
58 |
59 | ```javascript
60 | let users = ["Alice", "Bob", "Charlie"];
61 | console.log(users[0]); // Output: Alice
62 | ```
63 |
64 | 5. **Object**:
65 | Structured data stored as key–value pairs.
66 |
67 | ```javascript
68 | let user = {
69 | name: "Alice",
70 | age: 25,
71 | isAdmin: true
72 | };
73 | console.log(user.name); // Output: Alice
74 | ```
75 |
76 | ---
77 |
78 | ### **2.2 Operators and Control Structures**
79 |
80 | #### **Operators**
81 |
82 | 1. **Arithmetic Operators**:
83 |
84 | ```javascript
85 | let a = 10 + 5; // 15
86 | let b = 20 - 3; // 17
87 | let c = 6 * 2; // 12
88 | let d = 10 / 2; // 5
89 | ```
90 |
91 | 2. **Comparison Operators**:
92 |
93 | ```javascript
94 | console.log(5 > 3); // true
95 | console.log(5 === 5); // true (checks both value and type)
96 | console.log(5 != "5"); // false (== would ignore type)
97 | ```
98 |
99 | 3. **Logical Operators**:
100 |
101 | ```javascript
102 | let hasAccount = true;
103 | let isLoggedIn = false;
104 | console.log(hasAccount && isLoggedIn); // false (both must be true)
105 | console.log(hasAccount || isLoggedIn); // true (one is enough)
106 | ```
107 |
108 | #### **Control Structures**
109 |
110 | 1. **`if/else` Statement**:
111 |
112 | ```javascript
113 | let hour = 14;
114 | if (hour < 12) {
115 | console.log("Good morning!");
116 | } else {
117 | console.log("Good afternoon!");
118 | }
119 | ```
120 |
121 | 2. **`switch` Statement**:
122 |
123 | ```javascript
124 | let day = "Saturday";
125 | switch (day) {
126 | case "Saturday":
127 | console.log("Start of the week!");
128 | break;
129 | default:
130 | console.log("Another day!");
131 | }
132 | ```
133 |
134 | 3. **`for` Loop**:
135 |
136 | ```javascript
137 | for (let i = 0; i < 5; i++) {
138 | console.log(i); // Prints numbers 0 to 4
139 | }
140 | ```
141 |
142 | 4. **`while` Loop**:
143 |
144 | ```javascript
145 | let count = 3;
146 | while (count > 0) {
147 | console.log(count);
148 | count--;
149 | }
150 | ```
151 |
152 | ---
153 |
154 | ### **2.3 Functions**
155 |
156 | Functions are blocks of code that perform a specific task.
157 |
158 | #### **Regular Function Definition**
159 |
160 | ```javascript
161 | function greet(name) {
162 | return `Hello, ${name}!`;
163 | }
164 | console.log(greet("Alice")); // Output: Hello, Alice!
165 | ```
166 |
167 | #### **Arrow Functions (`=>`)**
168 |
169 | A shorter syntax, often for anonymous functions:
170 |
171 | ```javascript
172 | const add = (a, b) => a + b;
173 | console.log(add(2, 3)); // 5
174 | ```
175 |
176 | #### **Default Parameters**
177 |
178 | ```javascript
179 | function multiply(a, b = 2) {
180 | return a * b;
181 | }
182 | console.log(multiply(5)); // 10 (uses b = 2)
183 | ```
184 |
185 | ---
186 |
187 | ### **2.4 Modules**
188 |
189 | Modules help you organize code into separate files.
190 |
191 | #### **Exporting with `module.exports`**
192 |
193 | * **math.js**:
194 |
195 | ```javascript
196 | const PI = 3.14;
197 | function square(x) {
198 | return x * x;
199 | }
200 | module.exports = { PI, square };
201 | ```
202 |
203 | #### **Importing with `require`**
204 |
205 | * **main.js**:
206 |
207 | ```javascript
208 | const math = require('./math.js');
209 | console.log(math.PI); // 3.14
210 | console.log(math.square(4)); // 16
211 | ```
212 |
213 | ---
214 |
215 | ### **Hands-On Exercise for Chapter 2**
216 |
217 | 1. Write a function that takes two numbers and returns the larger one.
218 | 2. Create an array of user names and print each one to the console using a `for` loop.
219 | 3. Build a `config` object containing your bot’s token and command prefix.
220 |
221 | **Example for Exercise 1**:
222 |
223 | ```javascript
224 | function findMax(a, b) {
225 | return a > b ? a : b;
226 | }
227 | console.log(findMax(10, 5)); // 10
228 | ```
229 |
230 | ---
231 |
232 | ### **Key Takeaways for Chapter 2**
233 |
234 | * Always use `===` instead of `==` to check value **and** type.
235 | * Prefer `const` and `let` over `var`.
236 | * Arrow functions help preserve the meaning of `this` in objects (we’ll explore this in later chapters).
237 |
238 | ---
239 |
240 | In the next chapter, you’ll learn about **Node.js and npm** and how to manage packages! 🚀
--------------------------------------------------------------------------------
/javascript/en/saeson3.md:
--------------------------------------------------------------------------------
1 | ## **Chapter 3: Introduction to Node.js and npm**
2 |
3 | ---
4 |
5 | ### **3.1 What Is Node.js?**
6 |
7 | Node.js is a **runtime environment** for JavaScript that lets you run JavaScript code **outside the browser** (for example, on a server or your local machine).
8 |
9 | #### **Why Is Node.js Ideal for Discord Bots?**
10 |
11 | * **Non-Blocking:**
12 | Node.js executes code asynchronously, meaning time-consuming operations (like reading a file) won’t block the rest of your code.
13 |
14 | ```javascript
15 | // Example: reading a file without blocking other code
16 | const fs = require('fs');
17 | fs.readFile('file.txt', 'utf8', (err, data) => {
18 | console.log(data); // Runs after the file is read
19 | });
20 | console.log('This line runs first!');
21 | ```
22 |
23 | * **Event-Driven:**
24 | Node.js is built around events. For instance, when someone sends a message in Discord, a `messageCreate` event fires and your code can react to it.
25 |
26 | ---
27 |
28 | ### **3.2 Managing Packages with npm**
29 |
30 | **npm** (Node Package Manager) is a tool for installing, managing, and sharing JavaScript packages. Each package is a library or utility (such as `discord.js`).
31 |
32 | #### **Core npm Commands**
33 |
34 | 1. **Install a package:**
35 |
36 | ```bash
37 | npm install discord.js
38 | ```
39 | 2. **Uninstall a package:**
40 |
41 | ```bash
42 | npm uninstall discord.js
43 | ```
44 | 3. **Update a package:**
45 |
46 | ```bash
47 | npm update discord.js
48 | ```
49 |
50 | ---
51 |
52 | ### **3.3 The `package.json` File**
53 |
54 | The `package.json` file is the heart of any Node.js project. It holds project metadata and a list of **dependencies**.
55 |
56 | #### **Creating `package.json`**
57 |
58 | * Run this command to generate a `package.json` with default settings:
59 |
60 | ```bash
61 | npm init -y
62 | ```
63 | * Sample `package.json` contents:
64 |
65 | ```json
66 | {
67 | "name": "my-bot",
68 | "version": "1.0.0",
69 | "main": "index.js",
70 | "scripts": {
71 | "start": "node index.js"
72 | },
73 | "dependencies": {
74 | "discord.js": "^14.13.0"
75 | }
76 | }
77 | ```
78 |
79 | #### **Version Ranges (`^` and `~`)**
80 |
81 | * `^14.13.0`: Allows updates to **minor** versions (e.g., 14.14.0).
82 | * `~14.13.0`: Allows updates to **patch** versions only (e.g., 14.13.1).
83 |
84 | ---
85 |
86 | ### **3.4 Global vs. Local Package Installation**
87 |
88 | * **Local (default)** installs the package only in your current project:
89 |
90 | ```bash
91 | npm install discord.js
92 | ```
93 | * **Global** installs the package system-wide (useful for CLI tools):
94 |
95 | ```bash
96 | npm install -g nodemon
97 | ```
98 |
99 | ---
100 |
101 | ### **3.5 Running Your Project with npm Scripts**
102 |
103 | You can define shortcut commands inside `package.json`:
104 |
105 | ```json
106 | "scripts": {
107 | "start": "node index.js",
108 | "dev": "nodemon index.js"
109 | }
110 | ```
111 |
112 | * Run these scripts with:
113 |
114 | ```bash
115 | npm run dev
116 | ```
117 |
118 | ---
119 |
120 | ### **Hands-On Exercise for Chapter 3**
121 |
122 | 1. Create a new folder and run `npm init -y` to generate a `package.json`.
123 | 2. Install the `chalk` package to print colored text in the console:
124 |
125 | ```bash
126 | npm install chalk
127 | ```
128 | 3. Create an `index.js` file with this code:
129 |
130 | ```javascript
131 | const chalk = require('chalk');
132 | console.log(chalk.green('Hello, world!'));
133 | ```
134 | 4. Run your project:
135 |
136 | ```bash
137 | node index.js
138 | ```
139 |
140 | ---
141 |
142 | ### **Common Issues & Solutions**
143 |
144 | * **`npm install` errors:**
145 |
146 | * Check your internet connection.
147 | * Clear the cache: `npm cache clean --force`.
148 | * **Permission Denied (EACCES) errors:**
149 |
150 | * On macOS/Linux, use `sudo` for global installs.
151 | * On Windows, run PowerShell as Administrator.
152 |
153 | ---
154 |
155 | ### **Key Takeaways**
156 |
157 | * Always install project-specific dependencies (like `discord.js`) locally, not globally.
158 | * Add `node_modules` to your `.gitignore` (it can get very large).
159 | * Update Node.js by downloading the latest version from the [official website](https://nodejs.org).
160 |
161 | ---
162 |
163 | In the next chapter, you’ll learn **getting started with discord.js** and build your first full-fledged bot! 🚀
--------------------------------------------------------------------------------
/javascript/en/saeson4.md:
--------------------------------------------------------------------------------
1 | ## **Chapter 4: Getting Started with discord.js**
2 |
3 | ---
4 |
5 | ### **4.1 Introduction to the discord.js Library**
6 |
7 | `discord.js` is a powerful and flexible library for building Discord bots with JavaScript/Node.js.
8 |
9 | #### **Why discord.js?**
10 |
11 | * **Beginner-Friendly:** Easier to learn compared to other libraries (like `Eris`).
12 | * **Secure & Up-to-Date:** Regularly maintained and compatible with the latest Discord API changes.
13 | * **Excellent Documentation:** The [official docs](https://discord.js.org) are comprehensive and include examples.
14 |
15 | ---
16 |
17 | ### **4.2 Core Structure of a Bot**
18 |
19 | Every Discord bot using `discord.js` has three main parts:
20 |
21 | 1. **Client:** Connects your bot to Discord.
22 | 2. **Events:** Handles events (like receiving a message).
23 | 3. **Commands:** Executes user commands.
24 |
25 | ---
26 |
27 | ### **4.3 Connecting Your Bot to Discord**
28 |
29 | #### **Initial Setup Steps**
30 |
31 | 1. **Create a `Client`:**
32 |
33 | ```javascript
34 | const { Client, GatewayIntentBits } = require('discord.js');
35 | const client = new Client({
36 | intents: [
37 | GatewayIntentBits.Guilds, // Access to guild information
38 | GatewayIntentBits.GuildMessages, // Receive message events
39 | GatewayIntentBits.MessageContent // Read message content
40 | ]
41 | });
42 | ```
43 |
44 | 2. **Log In with Your Token:**
45 |
46 | ```javascript
47 | client.login('YOUR_BOT_TOKEN');
48 | ```
49 |
50 | 3. **Handle the `ready` Event:**
51 |
52 | ```javascript
53 | client.on('ready', () => {
54 | console.log(`✅ ${client.user.tag} is now online!`);
55 | });
56 | ```
57 |
58 | ---
59 |
60 | ### **4.4 Responding to User Messages**
61 |
62 | Use the `messageCreate` event to listen for and respond to messages:
63 |
64 | ```javascript
65 | client.on('messageCreate', (message) => {
66 | // Ignore messages from other bots
67 | if (message.author.bot) return;
68 |
69 | // Reply to "hi"
70 | if (message.content === 'hi') {
71 | message.reply('Hello! How are you? 😊');
72 | }
73 | });
74 | ```
75 |
76 | ---
77 |
78 | ### **4.5 Creating Your First Command (Ping–Pong)**
79 |
80 | ```javascript
81 | client.on('messageCreate', (message) => {
82 | if (message.content === '!ping') {
83 | const start = Date.now();
84 | message.reply('Calculating ping...').then((sentMessage) => {
85 | const latency = Date.now() - start;
86 | sentMessage.edit(`🏓 Pong! Latency: ${latency}ms`);
87 | });
88 | }
89 | });
90 | ```
91 |
92 | ---
93 |
94 | ### **4.6 Working with Message Properties**
95 |
96 | Every `message` object contains useful information:
97 |
98 | * **Content:** `message.content`
99 | * **Author:** `message.author.tag`
100 | * **Channel:** `message.channel.name`
101 | * **Guild:** `message.guild.name`
102 |
103 | **Example:**
104 |
105 | ```javascript
106 | client.on('messageCreate', (message) => {
107 | console.log(
108 | `Message from ${message.author.tag} in #${message.channel.name}: ${message.content}`
109 | );
110 | });
111 | ```
112 |
113 | ---
114 |
115 | ### **Hands-On Exercise for Chapter 4**
116 |
117 | 1. Create a command `!time` that replies with the current time.
118 | 2. Make a `!user` command that returns the author’s username and tag.
119 | 3. (Optional) Implement `!purge` to delete a specified number of messages.
120 |
121 | **Example for Exercise 1:**
122 |
123 | ```javascript
124 | if (message.content === '!time') {
125 | const time = new Date().toLocaleTimeString('en-US');
126 | message.reply(`Current time: ${time}`);
127 | }
128 | ```
129 |
130 | ---
131 |
132 | ### **Common Issues & Solutions**
133 |
134 | * **Bot Won’t Go Online:**
135 |
136 | * Verify your token is correct.
137 | * Check your internet connection.
138 | * Ensure the required intents are enabled in the Developer Portal ([Enabling Intents Guide](https://discordjs.guide/preparations/setting-up-a-bot-application.html#creating-your-bot)).
139 |
140 | * **Bot Doesn’t Respond to Messages:**
141 |
142 | * Add the `MessageContent` intent.
143 | * Confirm the bot is invited to your server.
144 |
145 | ---
146 |
147 | ### **Key Tips**
148 |
149 | * Enable **Gateway Intents** in the [Discord Developer Portal](https://discord.com/developers/applications).
150 | * **Never** commit your bot token to public code—use a `.env` file (covered in Chapter 7).
151 | * For more advanced commands, switch to **Slash Commands** (covered in Chapter 6).
152 |
153 | ---
154 |
155 | In the next chapter, you’ll learn **how to build more advanced commands** and work with **Embeds**! 🚀
--------------------------------------------------------------------------------
/javascript/en/saeson5.md:
--------------------------------------------------------------------------------
1 | ## **Chapter 5: Building Advanced Commands and Working with Embeds**
2 |
3 | ---
4 |
5 | ### **5.1 Handling Prefix Commands**
6 |
7 | To build more sophisticated commands, you need to parse the user’s message.
8 |
9 | #### **Command Processing Steps**
10 |
11 | 1. **Check the prefix**:
12 |
13 | ```javascript
14 | const prefix = '!'; // Command prefix (e.g., !ping)
15 | if (!message.content.startsWith(prefix)) return;
16 | ```
17 | 2. **Split command and arguments**:
18 |
19 | ```javascript
20 | const args = message.content.slice(prefix.length).trim().split(/ +/);
21 | const command = args.shift().toLowerCase(); // e.g., "ping"
22 | ```
23 |
24 | **Example**:
25 |
26 | ```javascript
27 | client.on('messageCreate', (message) => {
28 | if (!message.content.startsWith('!') || message.author.bot) return;
29 |
30 | const args = message.content.slice(1).split(/ +/);
31 | const command = args.shift().toLowerCase();
32 |
33 | if (command === 'announce') {
34 | const text = args.join(' ');
35 | message.channel.send(`📢 ${text.toUpperCase()}`);
36 | }
37 | });
38 | ```
39 |
40 | ---
41 |
42 | ### **5.2 Creating Rich Embeds**
43 |
44 | Embeds let you send richly formatted, structured messages.
45 |
46 | #### **Using `EmbedBuilder`**
47 |
48 | ```javascript
49 | const { EmbedBuilder } = require('discord.js');
50 |
51 | const exampleEmbed = new EmbedBuilder()
52 | .setColor(0x0099FF) // Sidebar color in HEX
53 | .setTitle('Embed Title') // Title
54 | .setDescription('General info')// Description
55 | .addFields( // Fields
56 | { name: 'Field 1', value: 'Value 1', inline: true },
57 | { name: 'Field 2', value: 'Value 2', inline: true }
58 | )
59 | .setImage('https://example.com/image.png') // Main image
60 | .setTimestamp(); // Add current timestamp
61 |
62 | message.channel.send({ embeds: [exampleEmbed] });
63 | ```
64 |
65 | #### **Practical Example (`!user` command)**
66 |
67 | ```javascript
68 | if (command === 'user') {
69 | const user = message.author;
70 | const embed = new EmbedBuilder()
71 | .setColor('Random')
72 | .setTitle('User Information')
73 | .setThumbnail(user.displayAvatarURL())
74 | .addFields(
75 | { name: 'Tag', value: user.tag },
76 | { name: 'ID', value: user.id },
77 | { name: 'Account Created', value: user.createdAt.toLocaleDateString('en-US') }
78 | );
79 |
80 | message.channel.send({ embeds: [embed] });
81 | }
82 | ```
83 |
84 | ---
85 |
86 | ### **5.3 Administrative Commands**
87 |
88 | Commands that require special permissions (e.g., deleting messages).
89 |
90 | #### **The `!purge` Command**
91 |
92 | ```javascript
93 | if (command === 'purge') {
94 | // Check Manage Messages permission
95 | if (!message.member.permissions.has('ManageMessages')) {
96 | return message.reply('❌ You don’t have permission to use this!');
97 | }
98 |
99 | const amount = parseInt(args[0]) || 10; // Default to 10 messages
100 | if (isNaN(amount) || amount < 1 || amount > 100) {
101 | return message.reply('Please enter a number between 1 and 100!');
102 | }
103 |
104 | message.channel.bulkDelete(amount + 1) // +1 to delete the purge command itself
105 | .then(() => {
106 | message.channel.send(`✅ Deleted ${amount} messages!`).then(msg => {
107 | setTimeout(() => msg.delete(), 5000);
108 | });
109 | })
110 | .catch(console.error);
111 | }
112 | ```
113 |
114 | ---
115 |
116 | ### **5.4 Adding Reactions**
117 |
118 | Use reactions for interactive features (like polls).
119 |
120 | #### **Poll Example (`!poll` command)**
121 |
122 | ```javascript
123 | if (command === 'poll') {
124 | const question = args.join(' ');
125 | if (!question) return message.reply('Please provide a poll question!');
126 |
127 | const pollEmbed = new EmbedBuilder()
128 | .setColor('#FFD700')
129 | .setTitle('📊 Poll Time')
130 | .setDescription(question)
131 | .addFields({ name: 'Instructions', value: 'React with ✅ or ❌!' });
132 |
133 | message.channel.send({ embeds: [pollEmbed] }).then(pollMessage => {
134 | pollMessage.react('✅');
135 | pollMessage.react('❌');
136 | });
137 | }
138 | ```
139 |
140 | ---
141 |
142 | ### **Hands-On Exercise for Chapter 5**
143 |
144 | 1. Create a `!level` command that displays a user’s XP level in an embed (store data in an array or simple JSON).
145 | 2. Build a `!help` command that lists all bot commands in a neatly organized embed.
146 | 3. (Optional) Implement a `!ban` command to ban a user by ID.
147 |
148 | ---
149 |
150 | ### **Common Issues & Solutions**
151 |
152 | * **Embed Doesn’t Send:**
153 |
154 | * Ensure you pass it as `{ embeds: [embed] }`, not `embed: embed`.
155 | * Verify your color value is valid.
156 | * **Permission Errors:**
157 |
158 | * Grant the bot **Manage Messages** permission in your server settings.
159 | * Use `message.member.permissions.has()` to check user permissions.
160 |
161 | ---
162 |
163 | ### **Key Tips**
164 |
165 | * No field in an embed may exceed **1024 characters**.
166 | * Use `setFooter()` to add footer text.
167 | * Access guild information via `message.guild`.
168 |
169 | ---
170 |
171 | In the next chapter, you’ll explore **advanced concepts** like **Slash Commands**, **error handling**, and **database integration**! 🚀
--------------------------------------------------------------------------------
/javascript/en/saeson6.md:
--------------------------------------------------------------------------------
1 | ## **Chapter 6: Advanced Concepts**
2 |
3 | ---
4 |
5 | ### **6.1 Error Handling**
6 |
7 | Every bot can run into errors! Proper error handling ensures your bot continues running instead of crashing.
8 |
9 | #### **Using `try/catch`**
10 |
11 | ```javascript
12 | client.on('messageCreate', async (message) => {
13 | try {
14 | // Code that might throw (e.g., calling an API)
15 | await someRiskyOperation();
16 | } catch (error) {
17 | console.error('An error occurred:', error);
18 | message.reply('⚠️ An error occurred! Please try again later.');
19 | }
20 | });
21 | ```
22 |
23 | #### **Logging Errors to a File**
24 |
25 | * Append errors to a log file for later review:
26 |
27 | ```javascript
28 | const fs = require('fs');
29 | fs.appendFileSync('errors.log', `${new Date().toISOString()}: ${error.stack}\n`);
30 | ```
31 |
32 | ---
33 |
34 | ### **6.2 Slash Commands**
35 |
36 | Slash commands (`/command`) offer a better user experience and don’t require a prefix.
37 |
38 | #### **Registering Slash Commands**
39 |
40 | 1. **Define the command in code**:
41 |
42 | ```javascript
43 | const { SlashCommandBuilder } = require('discord.js');
44 |
45 | module.exports = {
46 | data: new SlashCommandBuilder()
47 | .setName('ping')
48 | .setDescription('Check the bot’s ping'),
49 | async execute(interaction) {
50 | await interaction.reply('🏓 Pong!');
51 | }
52 | };
53 | ```
54 | 2. **Register commands with Discord**:
55 |
56 | * **Guild-specific** (faster updates):
57 |
58 | ```javascript
59 | const rest = new REST().setToken(process.env.TOKEN);
60 | const commands = [pingCommand.data.toJSON()];
61 | await rest.put(
62 | Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID),
63 | { body: commands }
64 | );
65 | ```
66 | * **Global** (available in all servers):
67 |
68 | ```javascript
69 | await rest.put(
70 | Routes.applicationCommands(CLIENT_ID),
71 | { body: commands }
72 | );
73 | ```
74 |
75 | ---
76 |
77 | ### **6.3 Working with a Database**
78 |
79 | To store persistent data (like user XP), you’ll need a database.
80 |
81 | #### **Using a JSON File (Simple Approach)**
82 |
83 | ```javascript
84 | const fs = require('fs');
85 |
86 | // Load database
87 | let db = JSON.parse(fs.readFileSync('database.json'));
88 |
89 | // Update user XP
90 | db[message.author.id] = { xp: 100, level: 2 };
91 |
92 | // Save back to file
93 | fs.writeFileSync('database.json', JSON.stringify(db));
94 | ```
95 |
96 | #### **Using SQLite (More Advanced)**
97 |
98 | 1. **Install the package**:
99 |
100 | ```bash
101 | npm install better-sqlite3
102 | ```
103 | 2. **Connect and set up**:
104 |
105 | ```javascript
106 | const Database = require('better-sqlite3');
107 | const db = new Database('database.sqlite');
108 |
109 | // Create table if it doesn’t exist
110 | db.prepare(`
111 | CREATE TABLE IF NOT EXISTS users (
112 | id TEXT PRIMARY KEY,
113 | xp INTEGER DEFAULT 0,
114 | level INTEGER DEFAULT 1
115 | )
116 | `).run();
117 | ```
118 | 3. **Insert data**:
119 |
120 | ```javascript
121 | const insert = db.prepare('INSERT OR IGNORE INTO users (id, xp) VALUES (?, ?)');
122 | insert.run(message.author.id, 100);
123 | ```
124 |
125 | ---
126 |
127 | ### **6.4 XP Leveling System**
128 |
129 | **Practical JSON example:**
130 |
131 | ```javascript
132 | client.on('messageCreate', (message) => {
133 | if (message.author.bot) return;
134 |
135 | const userId = message.author.id;
136 | db[userId] = db[userId] || { xp: 0, level: 1 };
137 | db[userId].xp += 10; // Award 10 XP per message
138 |
139 | // Level up check
140 | if (db[userId].xp >= db[userId].level * 100) {
141 | db[userId].level += 1;
142 | message.channel.send(
143 | `🎉 ${message.author} reached level ${db[userId].level}!`
144 | );
145 | }
146 |
147 | fs.writeFileSync('database.json', JSON.stringify(db));
148 | });
149 | ```
150 |
151 | ---
152 |
153 | ### **Hands-On Exercise for Chapter 6**
154 |
155 | 1. Create a slash command `/time` that replies with the current time.
156 | 2. Use SQLite to create a table for polls and store vote data.
157 | 3. Design a system that randomly awards a prize to a user each time they send a message.
158 |
159 | ---
160 |
161 | ### **Common Issues & Solutions**
162 |
163 | * **Slash commands not showing up**:
164 |
165 | * Wait 24–48 hours for global commands to propagate.
166 | * Verify you’re using correct `CLIENT_ID` and `GUILD_ID`.
167 | * **Database permission errors**:
168 |
169 | * Ensure your JSON/SQLite file is writable.
170 | * Use relative paths (e.g., `./database.json`).
171 |
172 | ---
173 |
174 | ### **Key Tips**
175 |
176 | * For production, consider robust databases like **PostgreSQL** or **MongoDB**.
177 | * Always **validate** user input before interacting with your database to prevent injection attacks.
178 | * Store sensitive info (token, DB credentials) in a **.env** file (covered in Chapter 7).
179 |
180 | ---
181 |
182 | In the next chapter, you’ll learn how to **deploy your bot** to a server and cover essential **security practices**! 🚀
--------------------------------------------------------------------------------
/javascript/en/saeson7.md:
--------------------------------------------------------------------------------
1 | ## **Chapter 7: Deployment, Maintenance, and Bot Security**
2 |
3 | ---
4 |
5 | ### **7.1 Preparing Your Bot for Deployment**
6 |
7 | Before uploading your bot to a server, make sure to:
8 |
9 | 1. **Hide Tokens and Sensitive Data**
10 |
11 | * Use the `dotenv` package and a `.env` file:
12 |
13 | ```env
14 | TOKEN=your_bot_token_here
15 | PREFIX=!
16 | ```
17 | * In your code:
18 |
19 | ```javascript
20 | require('dotenv').config();
21 | client.login(process.env.TOKEN);
22 | ```
23 |
24 | 2. **Remove Unnecessary Files**
25 |
26 | * Reinstall only production dependencies with:
27 |
28 | ```bash
29 | npm install --production
30 | ```
31 | * Audit your project for any leftover local or test files (e.g., `database.json`).
32 |
33 | ---
34 |
35 | ### **7.2 Deploying on Free Cloud Platforms**
36 |
37 | #### **Method 1: Replit**
38 |
39 | * Great for quick starts and small projects.
40 |
41 | 1. Create a new Replit project at [replit.com](https://replit.com).
42 | 2. Upload your code and add your `.env` variables in the Secrets panel.
43 | 3. Enable **Always On** so your bot runs 24/7.
44 |
45 | #### **Method 2: Railway or Heroku**
46 |
47 | * **Railway** (free tier with limits):
48 |
49 | 1. Link your GitHub repo to Railway.
50 | 2. Add environment variables in the project settings.
51 | 3. Use the free Railway domain for your bot’s webhook or web server.
52 |
53 | ---
54 |
55 | ### **7.3 Deploying on a Dedicated VPS**
56 |
57 | #### **Basic Steps for Ubuntu**
58 |
59 | 1. **SSH into Your Server**:
60 |
61 | ```bash
62 | ssh root@YOUR_SERVER_IP
63 | ```
64 | 2. **Install Node.js and npm**:
65 |
66 | ```bash
67 | curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
68 | sudo apt-get install -y nodejs
69 | ```
70 | 3. **Clone and Install Your Project**:
71 |
72 | ```bash
73 | git clone https://github.com/your-username/your-bot-repo.git
74 | cd your-bot-repo
75 | npm install
76 | ```
77 | 4. **Run with PM2 for Persistence**:
78 |
79 | ```bash
80 | sudo npm install -g pm2
81 | pm2 start index.js --name "my-bot"
82 | pm2 save
83 | pm2 startup
84 | ```
85 |
86 | ---
87 |
88 | ### **7.4 Bot Security Best Practices**
89 |
90 | 1. **Limit Bot Permissions**
91 |
92 | * In the Discord Developer Portal, enable only the **Intents** your bot needs.
93 | * Grant minimal **Bot Permissions** (e.g., only `Send Messages` and `Read Message History`).
94 |
95 | 2. **Mitigate DDoS and Spam**
96 |
97 | * Use rate limiting (e.g., via `express-rate-limit`) if you expose HTTP endpoints.
98 | * Audit your code to prevent accidental infinite loops or heavy CPU tasks.
99 |
100 | 3. **Regular Backups**
101 |
102 | * Automate backups of your database and key files (for example, with cron jobs).
103 |
104 | ---
105 |
106 | ### **7.5 Maintenance and Optimization**
107 |
108 | 1. **Resource Monitoring**
109 |
110 | * Check bot status with `pm2 list`.
111 | * View logs via `pm2 logs`.
112 |
113 | 2. **Updating Dependencies**
114 |
115 | ```bash
116 | npm outdated # Check for outdated packages
117 | npm update # Update to latest allowed versions
118 | ```
119 |
120 | 3. **Handling Unexpected Crashes**
121 |
122 | * Catch uncaught exceptions to prevent a full crash:
123 |
124 | ```javascript
125 | process.on('uncaughtException', (error) => {
126 | console.error('Uncaught Exception:', error);
127 | });
128 | ```
129 |
130 | ---
131 |
132 | ### **Hands-On Exercise for Chapter 7**
133 |
134 | 1. Deploy your bot on Replit or Railway and verify it stays online 24/7.
135 | 2. Use PM2 to run your bot on an Ubuntu server (local or remote).
136 | 3. Create a simple cron-based backup system for your database files.
137 |
138 | ---
139 |
140 | ### **Common Issues**
141 |
142 | * **Bot Goes Offline After a While**
143 |
144 | * Use PM2 or Docker for a resilient runtime.
145 | * Monitor server resources (CPU/RAM) to ensure you have enough capacity.
146 |
147 | * **`Missing Permissions` Errors**
148 |
149 | * Verify your bot’s permissions in the [Discord Developer Portal](https://discord.com/developers/applications).
150 |
151 | ---
152 |
153 | ### **Pro Tips**
154 |
155 | * For larger projects, containerize with **Docker** to ensure a consistent environment.
156 | * Track major version changes (e.g., discord.js v13 → v14) before upgrading.
157 | * Optionally, integrate **Webhooks** to receive real-time error or uptime notifications.
158 |
159 | ---
160 |
161 | Congratulations! After this chapter, you have everything you need to build, deploy, and maintain a professional Discord bot. 🎉
162 | *Next up: hands-on project challenges to solidify your skills!*
--------------------------------------------------------------------------------
/javascript/en/saeson8.md:
--------------------------------------------------------------------------------
1 | ## **Chapter 8: Practical Projects to Solidify Your Skills**
2 |
3 | ---
4 |
5 | ### **8.1 Project 1: Poll Bot**
6 |
7 | **Goal:** Build a bot that, with the command `!poll [question]`, creates a reaction-based poll and tracks results.
8 |
9 | #### **Implementation Steps:**
10 |
11 | 1. **Receive the Question & Create an Embed**
12 |
13 | ```javascript
14 | client.on('messageCreate', async (message) => {
15 | if (!message.content.startsWith('!poll') || message.author.bot) return;
16 | const question = message.content.slice(5).trim();
17 | if (!question) return message.reply('Please provide a poll question!');
18 |
19 | const pollEmbed = new EmbedBuilder()
20 | .setColor('#5865F2')
21 | .setTitle('📊 New Poll')
22 | .setDescription(question)
23 | .addFields({ name: 'Options', value: '✅ = Yes\n❌ = No' });
24 |
25 | const pollMessage = await message.channel.send({ embeds: [pollEmbed] });
26 | await pollMessage.react('✅');
27 | await pollMessage.react('❌');
28 | });
29 | ```
30 |
31 | 2. **Collect Results**
32 |
33 | ```javascript
34 | client.on('messageReactionAdd', async (reaction, user) => {
35 | if (user.bot) return;
36 | const embed = reaction.message.embeds[0];
37 | if (embed?.title === '📊 New Poll') {
38 | const yesCount = reaction.message.reactions.cache.get('✅')?.count || 0;
39 | const noCount = reaction.message.reactions.cache.get('❌')?.count || 0;
40 | // Store or display the counts as needed
41 | }
42 | });
43 | ```
44 |
45 | ---
46 |
47 | ### **8.2 Project 2: Music Bot**
48 |
49 | **Goal:** Create a bot that joins a voice channel and plays music.
50 |
51 | #### **Implementation Steps:**
52 |
53 | 1. **Install Required Packages**
54 |
55 | ```bash
56 | npm install @discordjs/voice @discordjs/opus ffmpeg-static ytdl-core
57 | ```
58 |
59 | 2. **Connect to a Voice Channel & Play**
60 |
61 | ```javascript
62 | const { joinVoiceChannel, createAudioPlayer, createAudioResource } = require('@discordjs/voice');
63 | const ytdl = require('ytdl-core');
64 |
65 | client.on('messageCreate', async (message) => {
66 | if (message.content.startsWith('!play')) {
67 | const voiceChannel = message.member.voice.channel;
68 | if (!voiceChannel) return message.reply('⚠️ You must join a voice channel first!');
69 |
70 | const connection = joinVoiceChannel({
71 | channelId: voiceChannel.id,
72 | guildId: voiceChannel.guild.id,
73 | adapterCreator: voiceChannel.guild.voiceAdapterCreator,
74 | });
75 |
76 | const stream = ytdl('https://youtu.be/VIDEO_ID', { filter: 'audioonly' });
77 | const resource = createAudioResource(stream);
78 | const player = createAudioPlayer();
79 |
80 | connection.subscribe(player);
81 | player.play(resource);
82 | }
83 | });
84 | ```
85 |
86 | ---
87 |
88 | ### **8.3 Project 3: XP Leveling System**
89 |
90 | **Goal:** Track user activity and assign levels based on XP.
91 |
92 | #### **Implementation Steps:**
93 |
94 | 1. **Store Data in JSON**
95 |
96 | ```javascript
97 | const fs = require('fs');
98 | let xpData = JSON.parse(fs.readFileSync('xp.json', 'utf8')) || {};
99 |
100 | client.on('messageCreate', (message) => {
101 | if (message.author.bot) return;
102 |
103 | const userId = message.author.id;
104 | xpData[userId] = xpData[userId] || { xp: 0, level: 1 };
105 |
106 | // Award random XP (5–15)
107 | xpData[userId].xp += Math.floor(Math.random() * 11) + 5;
108 |
109 | // Check for level-up
110 | const xpNeeded = xpData[userId].level * 100;
111 | if (xpData[userId].xp >= xpNeeded) {
112 | xpData[userId].level++;
113 | message.channel.send(`🎉 ${message.author} reached level ${xpData[userId].level}!`);
114 | }
115 |
116 | fs.writeFileSync('xp.json', JSON.stringify(xpData));
117 | });
118 | ```
119 |
120 | 2. **Create the `!level` Command**
121 |
122 | ```javascript
123 | if (message.content === '!level') {
124 | const userData = xpData[message.author.id] || { xp: 0, level: 1 };
125 | const embed = new EmbedBuilder()
126 | .setTitle('📊 Your Level')
127 | .addFields(
128 | { name: 'Level', value: userData.level.toString(), inline: true },
129 | { name: 'XP', value: userData.xp.toString(), inline: true }
130 | );
131 | message.channel.send({ embeds: [embed] });
132 | }
133 | ```
134 |
135 | ---
136 |
137 | ### **8.4 Project 4: Moderation Bot**
138 |
139 | **Goal:** Implement moderation commands like ban, mute, and bulk delete.
140 |
141 | #### **`!ban` Command Example**
142 |
143 | ```javascript
144 | if (command === 'ban') {
145 | if (!message.member.permissions.has('BanMembers')) {
146 | return message.reply('❌ You do not have permission to ban members!');
147 | }
148 |
149 | const target = message.mentions.users.first();
150 | if (!target) return message.reply('⚠️ Please mention a user to ban!');
151 |
152 | message.guild.members.ban(target.id)
153 | .then(() => message.reply(`✅ ${target.tag} has been banned!`))
154 | .catch(() => message.reply('⛔ Failed to ban the user!'));
155 | }
156 | ```
157 |
158 | ---
159 |
160 | ### **8.5 Project 5: Mini-Games Bot**
161 |
162 | **Goal:** Create simple interactive games.
163 |
164 | #### **`!coin` Command**
165 |
166 | ```javascript
167 | if (command === 'coin') {
168 | const result = Math.random() < 0.5 ? 'Heads' : 'Tails';
169 | message.reply(`I flipped a coin and got **${result}**!`);
170 | }
171 | ```
172 |
173 | #### **`!number` Command**
174 |
175 | ```javascript
176 | if (command === 'number') {
177 | const num = Math.floor(Math.random() * 100) + 1;
178 | message.reply(`Your random number is **${num}**`);
179 | }
180 | ```
181 |
182 | ---
183 |
184 | ### **Additional Challenges**
185 |
186 | 1. **Ticket Bot:** With `!ticket`, create a private support channel for the user.
187 | 2. **Dictionary Bot:** `!define [word]` fetches definitions from an API.
188 | 3. **Weather Bot:** `!weather [city]` displays current weather info.
189 |
190 | ---
191 |
192 | ### **Common Issues & Fixes**
193 |
194 | * **Music Bot Isn’t Playing:**
195 |
196 | * Ensure **FFmpeg** is installed (`npm install ffmpeg-static`).
197 | * Confirm the bot has joined the voice channel.
198 | * **XP System Not Saving Data:**
199 |
200 | * Use `fs.writeFileSync` after each update.
201 | * Verify the correct path to `xp.json`.
202 |
203 | ---
204 |
205 | ### **Final Tips**
206 |
207 | * Code projects **modularly** (each command in its own file).
208 | * Use **GitHub** for version control.
209 | * For more ideas, see [Discord Bot Ideas](https://github.com/discordjs/guide/discussions).
210 |
211 | ---
212 |
213 | **Course Complete!** 🎓
214 | You can now build, extend, and deploy professional Discord bots. Keep learning and create your own custom projects!
--------------------------------------------------------------------------------
/javascript/per/README.md:
--------------------------------------------------------------------------------
1 | # فهرست مطالب
2 |
3 | ### [**فصل ۱: مقدمه و آماده سازی محیط کار**](./saeson1.md)
4 | 1. **برنامه نویسی چیست؟**
5 | - چرا دیسکورد و Node.js؟
6 | - کاربرد ربات های دیسکورد.
7 | 2. **ابزار های مورد نیاز**
8 | - نصب Node.js و npm.
9 | - معرفی ویرایشگر کد (مثلاً VS Code).
10 | - ساخت بات در پنل توسعه دهندگان دیسکورد (Developer Portal).
11 | - دریافت توکن (Token) بات.
12 |
13 | ---
14 |
15 | ### [**فصل ۲: آشنایی با مفاهیم پایه جاوا اسکریپت**](./saeson2.md)
16 | 1. **متغیر ها و انواع داده**
17 | - `let`، `const`، `var`.
18 | - رشته ها، اعداد، بولین، آرایه ها، اشیاء.
19 | 2. **عملگر ها و ساختار های کنترلی**
20 | - عملگر های ریاضی، مقایسه ای و منطقی.
21 | - شرط (`if/else`، `switch`).
22 | - حلقه ها (`for`، `while`).
23 | 3. **توابع و ماژول ها**
24 | - تعریف توابع (عادی و Arrow Functions).
25 | - ورودی و خروجی توابع.
26 | - آشنایی با `require` و `module.exports`.
27 |
28 | ---
29 |
30 | ### [**فصل ۳: آشنایی با Node.js و npm**](./saeson3.md)
31 | 1. **Node.js چیست؟**
32 | - اجرای کد جاوا اسکریپت خارج از مرورگر.
33 | - رویداد محور و غیرمسدودکننده.
34 | 2. **مدیریت پکیج ها با npm**
35 | - نصب پکیج ها (مثلاً `npm install discord.js`).
36 | - فایل `package.json` و مدیریت وابستگی ها.
37 |
38 | ---
39 |
40 | ### [**فصل ۴: شروع کار با discord.js**](./saeson4.md)
41 | 1. **معرفی کتابخانه discord.js**
42 | - چرا discord.js؟
43 | - ساختار اصلی یک ربات دیسکورد.
44 | 2. **ساخت اولین ربات**
45 | - اتصال به دیسکورد با `Client` و توکن.
46 | - رویداد `ready` و پاسخ به لاگین موفق.
47 | - پاسخ به پیام های کاربران (رویداد `messageCreate`).
48 |
49 | ---
50 |
51 | ### [**فصل ۵: ساخت دستورات ساده**](./saeson5.md)
52 | 1. **پردازش دستورات**
53 | - شناسایی پیشوند دستورات (مثلاً `!ping`).
54 | - ارسال پاسخ به کاربر (`message.reply()`).
55 | 2. **کار با Embedها**
56 | - ساخت پیام های زیبا با `EmbedBuilder`.
57 | - افزودن فیلدها، رنگ و تصویر.
58 |
59 | ---
60 |
61 | ### [**فصل ۶: مفاهیم پیشرفته تر**](./saeson6.md)
62 | 1. **مدیریت خطا ها**
63 | - استفاده از `try/catch`.
64 | - جلوگیری از کرش ربات.
65 | 2. **کار با دستورات اسلشی (Slash Commands)**
66 | - ثبت دستورات جهانی/سروری.
67 | - پاسخ به تعاملات (`interaction.reply()`).
68 | 3. **ذخیره داده ها**
69 | - معرفی دیتابیس های ساده (مثلاً JSON فایل یا SQLite).
70 | - ذخیره تنظیمات یا اطلاعات کاربران.
71 |
72 | ---
73 |
74 | ### [**فصل ۷: انتشار و نگه داری ربات**]((./saeson7.md))
75 | 1. **Deploy ربات روی سرور**
76 | - استفاده از سرویس های رایگان (مثل Replit یا Railway).
77 | - اجرای ربات ۲۴/۷.
78 | 2. **بهینه سازی و امنیت**
79 | - پنهان کردن توکن با استفاده از `.env`.
80 | - مدیریت منابع و حافظه.
81 |
82 | ---
83 |
84 | ### [**فصل ۸: پروژه های عملی**](./saeson8.md)
85 | 1. **ساخت ربات نظرسنجی**
86 | - استفاده از Reactions و جمع آوری نتایج.
87 | 2. **ربات موزیک پلیر**
88 | - اتصال به چنل صوتی و پخش موزیک.
89 | 3. **سیستم سطح بندی کاربران (XP System)**
90 | - ردیابی فعالیت کاربران و اعتبارسنجی.
91 |
92 | ---
93 |
94 | ### **ضمیمه ها و منابع بیشتر**
95 | - لیست کامند های مفید discord.js.
96 | - لینک مستندات رسمی [discord.js](https://discord.js.org/#/).
97 | - جامعه های پشتیبانی (دیسکورد، Stack Overflow).
98 |
99 | ---
100 |
101 | ### **نکات کلیدی برای آموزش:**
102 | - هر بخش با مثال های ساده و کد های قابل اجرا شروع شود.
103 | - از تصاویر و اسکرین شات برای راهنمایی بصری استفاده شود.
104 | - تمرین های کوچک پس از هر درس برای تثبیت مفاهیم.
105 | - تاکید بر اشکال زدایی (Debugging) و خواندن خطا ها.
--------------------------------------------------------------------------------
/javascript/per/saeson1.md:
--------------------------------------------------------------------------------
1 | **فصل ۱: مقدمه و آماده سازی محیط کار**
2 |
3 | ---
4 |
5 | ### **۱.۱ برنامه نویسی چیست؟**
6 | برنامه نویسی یعنی نوشتن دستوراتی که کامپیوتر آن ها را اجرا می کند تا یک خروجی یا عملکرد خاص ایجاد شود.
7 | - **چرا دیسکورد و Node.js؟**
8 | - دیسکورد یک پلتفرم محبوب برای ساخت جوامع آنلاین است و ربات ها می توانند امکاناتی مثل مدیریت خودکار، بازی ها یا تعاملات هوشمند را به سرور ها اضافه کنند.
9 | - **Node.js** یک محیط اجرایی برای جاوا اسکریپت است که به شما اجازه می دهد کد هایتان را خارج از مرورگر (مثلاً روی سرور) اجرا کنید. این ابزار برای ساخت ربات های دیسکورد با کتابخانه `discord.js` ایده آل است.
10 |
11 | ---
12 |
13 | ### **۱.۲ ابزار های مورد نیاز**
14 | برای شروع، باید ابزار های زیر را آماده کنید:
15 |
16 | #### **۱.۲.۱ نصب Node.js و npm**
17 | 1. به سایت [Node.js](https://nodejs.org) بروید.
18 | 2. نسخه **LTS** (پشتیبانیشده) را دانلود و نصب کنید.
19 | 3. پس از نصب، ترمینال/CMD را باز کرده و دستور زیر را وارد کنید تا از نصب موفقیت آمیز مطمئن شوید:
20 |
21 | ```bash
22 | node -v # باید نسخه Node.js نمایش داده شود (مثلاً v18.12.1)
23 | npm -v # باید نسخه npm نمایش داده شود (مثلاً 8.19.2)
24 | ```
25 |
26 | #### **۱.۲.۲ ویرایشگر کد: VS Code**
27 | - VS Code یک ویرایشگر رایگان و محبوب است. آن را از [این لینک](https://code.visualstudio.com) دانلود و نصب کنید.
28 |
29 | #### **۱.۲.۳ ساخت بات در دیسکورد**
30 | 1. به [پنل توسعه دهندگان دیسکورد](https://discord.com/developers/applications) بروید.
31 | 2. روی **New Application** کلیک کنید و نامی برای ربات انتخاب کنید.
32 | 3. به بخش **Bot** در منوی سمت چپ بروید و روی **Add Bot** کلیک کنید.
33 | 4. **توکن (Token)** ربات را کپی و در جای امن نگه دارید (این توکن مانند رمز عبور ربات است!).
34 |
35 | 
36 | 
37 | 
38 | 
39 | 
40 | 
41 | 
42 | 
43 | 
44 |
45 | ---
46 |
47 | ### **۱.۳ شروع اولین پروژه**
48 | 1. یک پوشه جدید برای پروژه بسازید (مثلاً `my-first-bot`).
49 | 2. در VS Code، این پوشه را باز کنید.
50 | 3. در ترمینال VS Code، دستور زیر را اجرا کنید تا پروژه Node.js راه اندازی شود:
51 | ```bash
52 | npm init -y
53 | ```
54 | 4. کتابخانه `discord.js` را نصب کنید:
55 | ```bash
56 | npm install discord.js
57 | ```
58 |
59 | ---
60 |
61 | ### **۱.۴ تست اتصال ربات به دیسکورد**
62 | یک فایل `index.js` ایجاد کرده و کد زیر را در آن بنویسید:
63 |
64 | ```javascript
65 | const { Client, GatewayIntentBits } = require('discord.js');
66 | const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages] });
67 |
68 | client.on('ready', () => {
69 | console.log(`ربات با موفقیت لاگین کرد! نام: ${client.user.tag}`);
70 | });
71 |
72 | client.on('messageCreate', (message) => {
73 | if (message.content === 'سلام') {
74 | message.reply('سلام! چطوری؟');
75 | }
76 | });
77 |
78 | client.login('TOKEN_خود_را_اینجا_قرار_دهید');
79 | ```
80 | - توکن ربات را جایگزین `TOKEN_خود_را_اینجا_قرار_دهید` کنید.
81 | - ربات را با دستور زیر در ترمینال اجرا کنید:
82 | ```bash
83 | node index.js
84 | ```
85 | - اگر همه چیز درست باشد، ربات در دیسکورد آنلاین می شود و به پیام «سلام» پاسخ می دهد!
86 |
87 | ---
88 |
89 | ### **تمرین عملی فصل ۱**
90 | ۱. یک ربات جدید در دیسکورد ایجاد کنید و توکن آن را دریافت کنید.
91 | ۲. کد `index.js` را طبق مثال بالا بنویسید و ربات را اجرا کنید.
92 | ۳. در سرور دیسکورد، به ربات پیام «سلام» بفرستید و پاسخ آن را بررسی کنید.
93 |
94 | ---
95 |
96 | ### **مهم ترین نکات**
97 | - توکن ربات را **هرگز** با کسی به اشتراک نگذارید!
98 | - اگر ربات آنلاین نمی شود:
99 | - مطمئن شوید توکن را درست جایگذاری کرده اید.
100 | - اینترنت شما متصل است.
101 | - ربات را به سرور دیسکورد اضافه کرده اید (از طریق لینک **OAuth2** در پنل توسعه دهندگان).
102 |
103 | در فصل بعدی، با مفاهیم پایه جاوا اسکریپت آشنا خواهید شد! 🚀
--------------------------------------------------------------------------------
/javascript/per/saeson2.md:
--------------------------------------------------------------------------------
1 | **فصل ۲: آشنایی با مفاهیم پایه جاوا اسکریپت**
2 |
3 | ---
4 |
5 | ### **۲.۱ متغیر ها و انواع داده**
6 | متغیر ها مانند جعبه هایی هستند که داده ها را در خود ذخیره می کنند.
7 | #### **انواع متغیر ها**
8 | - **`let`**:
9 | برای تعریف متغیر هایی که مقدارشان **تغییر می کند**.
10 |
11 | ```javascript
12 | let age = 20;
13 | age = 21; // قابل تغییر است
14 | ```
15 |
16 | - **`const`**:
17 | برای تعریف متغیر هایی که مقدارشان **ثابت** است (تغییر نمی کند).
18 |
19 | ```javascript
20 | const PI = 3.14;
21 | // PI = 5; // خطا! مقدار const قابل تغییر نیست
22 | ```
23 |
24 | - **`var`**:
25 | قدیمیتر است و امروزه کمتر استفاده می شود (به دلیل مشکلات در **محدوده ی دسترسی**).
26 |
27 | #### **انواع داده (Data Types)**
28 | 1. **رشته (String)**:
29 | متن را در کوتیشن (`""` یا `''` یا ` `` `) نگه می دارد.
30 |
31 | ```javascript
32 | let name = "Alice";
33 | let message = 'سلام!';
34 | ```
35 |
36 | 2. **عدد (Number)**:
37 | شامل اعداد صحیح و اعشاری.
38 | ```javascript
39 | let price = 1000;
40 | let temperature = 23.5;
41 | ```
42 |
43 | 3. **بولین (Boolean)**:
44 | فقط دو مقدار `true` یا `false`.
45 | ```javascript
46 | let isOnline = true;
47 | let hasPermission = false;
48 | ```
49 |
50 | 4. **آرایه (Array)**:
51 | لیستی از داده ها با اندیس شماره گذاری شده.
52 | ```javascript
53 | let users = ["Alice", "Bob", "Charlie"];
54 | console.log(users[0]); // خروجی: Alice
55 | ```
56 |
57 | 5. **شیء (Object)**:
58 | داده های ساختار یافته با جفت های **کلید-مقدار**.
59 |
60 | ```javascript
61 | let user = {
62 | name: "Alice",
63 | age: 25,
64 | isAdmin: true
65 | };
66 | console.log(user.name); // خروجی: Alice
67 | ```
68 |
69 | ---
70 |
71 | ### **۲.۲ عملگر ها و ساختار های کنترلی**
72 | #### **عملگر ها (Operators)**
73 | 1. **عملگر های ریاضی**:
74 | ```javascript
75 | let a = 10 + 5; // 15
76 | let b = 20 - 3; // 17
77 | let c = 6 * 2; // 12
78 | let d = 10 / 2; // 5
79 | ```
80 |
81 | 2. **عملگر های مقایسهای**:
82 |
83 | ```javascript
84 | console.log(5 > 3); // true
85 | console.log(5 === 5); // true (بررسی مقدار و نوع داده)
86 | console.log(5 != "5"); // false (چون == نوع داده را نادیده می گیرد)
87 | ```
88 |
89 | 3. **عملگر های منطقی**:
90 |
91 | ```javascript
92 | let hasAccount = true;
93 | let isLoggedIn = false;
94 | console.log(hasAccount && isLoggedIn); // false (هر دو باید true باشند)
95 | console.log(hasAccount || isLoggedIn); // true (یکی کافی است)
96 | ```
97 |
98 | #### **ساختار های کنترلی**
99 | 1. **شرط `if/else`**:
100 |
101 | ```javascript
102 | let hour = 14;
103 | if (hour < 12) {
104 | console.log("صبح بخیر!");
105 | } else {
106 | console.log("عصر بخیر!");
107 | }
108 | ```
109 |
110 | 2. **شرط `switch`**:
111 |
112 | ```javascript
113 | let day = "شنبه";
114 | switch (day) {
115 | case "شنبه":
116 | console.log("اول هفته!");
117 | break;
118 | default:
119 | console.log("روز دیگری است!");
120 | }
121 | ```
122 |
123 | 3. **حلقه `for`**:
124 |
125 | ```javascript
126 | for (let i = 0; i < 5; i++) {
127 | console.log(i); // اعداد ۰ تا ۴ چاپ می شود
128 | }
129 | ```
130 |
131 | 4. **حلقه `while`**:
132 | ```javascript
133 | let count = 3;
134 | while (count > 0) {
135 | console.log(count);
136 | count--;
137 | }
138 | ```
139 |
140 | ---
141 |
142 | ### **۲.۳ توابع (Functions)**
143 | توابع بلوک هایی از کد هستند که یک وظیفه خاص را انجام می دهند.
144 |
145 | #### **تعریف تابع عادی**
146 |
147 | ```javascript
148 | function greet(name) {
149 | return `سلام ${name}!`;
150 | }
151 | console.log(greet("Alice")); // خروجی: سلام Alice!
152 | ```
153 |
154 | #### **توابع Arrow (=>)**
155 | نسخه کوتاه تر توابع (معمولاً برای توابع بی نام):
156 | ```javascript
157 | const add = (a, b) => a + b;
158 | console.log(add(2, 3)); // 5
159 | ```
160 |
161 | #### **پارامتر های پیشفرض**
162 |
163 | ```javascript
164 | function multiply(a, b = 2) {
165 | return a * b;
166 | }
167 | console.log(multiply(5)); // 10 (b=2 استفاده می شود)
168 | ```
169 |
170 | ---
171 |
172 | ### **۲.۴ ماژول ها (Modules)**
173 | ماژول ها کمک می کنند کدها را در فایل های مختلف سازماندهی کنید.
174 |
175 | #### **ارسال داده با `module.exports`**
176 | - فایل `math.js`:
177 | ```javascript
178 | const PI = 3.14;
179 | function square(x) { return x * x; }
180 | module.exports = { PI, square };
181 | ```
182 |
183 | #### **دریافت داده با `require`**
184 | - فایل `main.js`:
185 | ```javascript
186 | const math = require('./math.js');
187 | console.log(math.PI); // 3.14
188 | console.log(math.square(4)); // 16
189 | ```
190 |
191 | ---
192 |
193 | ### **تمرین عملی فصل ۲**
194 | ۱. تابعی بنویسید که دو عدد را دریافت کند و بزرگتر را برگرداند.
195 | ۲. آرایهای از نام کاربران بسازید و با حلقه `for` همه را در کنسول چاپ کنید.
196 | ۳. یک شیء `config` بسازید که شامل توکن ربات و پیشوند دستورات باشد.
197 |
198 | **مثال تمرین ۱**:
199 | ```javascript
200 | function findMax(a, b) {
201 | return a > b ? a : b;
202 | }
203 | console.log(findMax(10, 5)); // 10
204 | ```
205 |
206 | ---
207 |
208 | ### **نکات مهم فصل**
209 | - همیشه از `===` به جای `==` استفاده کنید تا نوع داده بررسی شود.
210 | - برای تعریف متغیر ها اولویت با `const` و `let` است (از `var` استفاده نکنید).
211 | - توابع Arrow برای حفظ مفهوم `this` در آبجکت ها مفیدند (در فصل های بعدی توضیح داده می شود).
212 |
213 | ---
214 |
215 | در فصل بعدی، با **Node.js و npm** آشنا خواهید شد و یاد میگیرید چگونه پکیج ها را مدیریت کنید! 🚀
--------------------------------------------------------------------------------
/javascript/per/saeson3.md:
--------------------------------------------------------------------------------
1 | **فصل ۳: آشنایی با Node.js و npm**
2 |
3 | ---
4 |
5 | ### **۳.۱ Node.js چیست؟**
6 | Node.js یک **محیط اجرایی** (Runtime Environment) برای زبان جاوا اسکریپت است که به شما اجازه می دهد کدهای جاوا اسکریپت را **خارج از مرورگر** (مثلاً روی سرور یا کامپیوتر شخصی) اجرا کنید.
7 |
8 | #### **چرا Node.js برای ربات های دیسکورد مناسب است؟**
9 | - **غیرمسدودکننده (Non-Blocking)**:
10 | Node.js کدها را به صورت ناهمزمان (Asynchronous) اجرا می کند، یعنی اگر یک عملیات زمانبر (مثل خواندن فایل) انجام شود، بقیه کدها منتظر نمی مانند و اجرا می شوند.
11 |
12 | ```javascript
13 | // مثال: خواندن فایل بدون مسدود کردن سایر کدها
14 | const fs = require('fs');
15 | fs.readFile('file.txt', 'utf8', (err, data) => {
16 | console.log(data); // پس از خواندن فایل اجرا می شود
17 | });
18 | console.log('این خط اول اجرا می شود!');
19 | ```
20 |
21 | - **رویدادمحور (Event-Driven)**:
22 | Node.js بر پایه رویداد ها کار می کند. مثلاً وقتی کاربری در دیسکورد پیامی ارسال می کند، یک رویداد (`messageCreate`) رخ می دهد و کد شما به آن واکنش نشان می دهد.
23 |
24 | ---
25 |
26 | ### **۳.۲ مدیریت پکیج ها با npm**
27 | **npm** (مخفف Node Package Manager) یک ابزار برای نصب، مدیریت و اشتراک گذاری پکیج های جاوا اسکریپت است. هر پکیج یک کتابخانه یا ابزار آماده است (مثل `discord.js`).
28 |
29 | #### **کاربرد های اصلی npm**
30 | 1. **نصب پکیج ها**:
31 | ```bash
32 | npm install discord.js
33 | ```
34 | 2. **حذف پکیج ها**:
35 | ```bash
36 | npm uninstall discord.js
37 | ```
38 | 3. **بروزرسانی پکیج ها**:
39 | ```bash
40 | npm update discord.js
41 | ```
42 |
43 | ---
44 |
45 | ### **۳.۳ فایل `package.json`**
46 | این فایل قلب پروژه های Node.js است و شامل اطلاعات پروژه و لیست **وابستگی ها** (Dependencies) می شود.
47 |
48 | #### **ساخت `package.json`**
49 | - دستور زیر یک فایل `package.json` جدید میسازد:
50 | ```bash
51 | npm init -y
52 | ```
53 | - محتوای نمونه:
54 | ```json
55 | {
56 | "name": "my-bot",
57 | "version": "1.0.0",
58 | "main": "index.js",
59 | "scripts": {
60 | "start": "node index.js"
61 | },
62 | "dependencies": {
63 | "discord.js": "^14.13.0"
64 | }
65 | }
66 | ```
67 |
68 | #### **نکات مهم**
69 | - **ورژن پکیج ها (`^` و `~`)**:
70 | - `^14.13.0`: اجازه بروزرسانی به ورژن های **جزئی** جدیدتر را می دهد (مثلاً ۱۴.۱۴.۰).
71 | - `~14.13.0`: فقط اجازه بروزرسانی به ورژن های **پچ** را می دهد (مثلاً ۱۴.۱۳.۱).
72 |
73 | ---
74 |
75 | ### **۳.۴ نصب پکیج ها به صورت Global vs Local**
76 | - **نصب Local (پیشفرض)**:
77 | پکیج فقط در پروژه فعلی قابل استفاده است.
78 | ```bash
79 | npm install discord.js
80 | ```
81 | - **نصب Global**:
82 | پکیج در کل سیستم نصب می شود (برای ابزار های CLI مناسب است).
83 | ```bash
84 | npm install -g nodemon
85 | ```
86 |
87 | ---
88 |
89 | ### **۳.۵ اجرای پروژه با npm Scripts**
90 | از فایل `package.json` می توانید برای تعریف دستورات سریع استفاده کنید:
91 | ```json
92 | "scripts": {
93 | "start": "node index.js",
94 | "dev": "nodemon index.js"
95 | }
96 | ```
97 | - اجرای اسکریپت ها:
98 | ```bash
99 | npm run dev
100 | ```
101 |
102 | ---
103 |
104 | ### **تمرین عملی فصل ۳**
105 | ۱. یک پوشه جدید بسازید و با `npm init -y` فایل `package.json` ایجاد کنید.
106 | ۲. پکیج `chalk` را نصب کنید تا متن های رنگی در کنسول چاپ کنید.
107 | ۳. فایل `index.js` بسازید و کد زیر را در آن بنویسید:
108 |
109 | ```javascript
110 | const chalk = require('chalk');
111 | console.log(chalk.green('سلام دنیا!'));
112 | ```
113 | ۴. پروژه را با دستور `node index.js` اجرا کنید.
114 |
115 | ---
116 |
117 | ### **مشکلات رایج و راه حل ها**
118 | - **خطای `npm install`**:
119 | - اتصال اینترنت را بررسی کنید.
120 | - از دستور `npm cache clean --force` استفاده کنید.
121 | - **خطای دسترسی (Permission Denied)**:
122 | - برای نصب Global از `sudo` (در مک/لینوکس) یا PowerShell با حقوق Administrator (در ویندوز) استفاده کنید.
123 |
124 | ---
125 |
126 | ### **نکات کلیدی**
127 | - همیشه پکیج های اصلی پروژه (مثل `discord.js`) را با `npm install` نصب کنید، نه به صورت Global.
128 | - فایل `node_modules` را در `.gitignore` قرار دهید (چون حجم بالایی دارد).
129 | - برای به روز رسانی Node.js، از [وبسایت رسمی](https://nodejs.org) نسخه جدیدتر دانلود کنید.
130 |
131 | ---
132 |
133 | در فصل بعدی، **شروع کار با کتابخانه discord.js** را یاد خواهید گرفت و اولین ربات خود را توسعه می دهید! 🚀
--------------------------------------------------------------------------------
/javascript/per/saeson4.md:
--------------------------------------------------------------------------------
1 | **فصل ۴: شروع کار با discord.js**
2 |
3 | ---
4 |
5 | ### **۴.۱ معرفی کتابخانه discord.js**
6 | `discord.js` یک کتابخانه قدرتمند و انعطاف پذیر برای ساخت ربات های دیسکورد با جاوا اسکریپت/Node.js است.
7 |
8 | #### **چرا discord.js؟**
9 | - **ساده و مبتدی پسند**: نسبت به کتابخانه های دیگر (مثل `Eris`) یادگیری آسانتری دارد.
10 | - **امن و به روز**: بهطور مرتب آپدیت می شود و با آخرین تغییرات API دیسکورد سازگار است.
11 | - **مستندات عالی**: [مستندات رسمی](https://discord.js.org) آن جامع و همراه با مثال است.
12 |
13 | ---
14 |
15 | ### **۴.۲ ساختار اصلی یک ربات**
16 | هر ربات دیسکورد با `discord.js` سه بخش اصلی دارد:
17 | 1. **Client**: اتصال ربات به دیسکورد.
18 | 2. **Events**: پردازش رویداد ها (مثل دریافت پیام).
19 | 3. **Commands**: اجرای دستورات کاربران.
20 |
21 | ---
22 |
23 | ### **۴.۳ اتصال ربات به دیسکورد**
24 | #### **مراحل راه اندازی اولیه**
25 | 1. **ایجاد یک `Client`**:
26 |
27 | ```javascript
28 | const { Client, GatewayIntentBits } = require('discord.js');
29 | const client = new Client({
30 | intents: [
31 | GatewayIntentBits.Guilds, // دسترسی به سرور ها
32 | GatewayIntentBits.GuildMessages, // دریافت پیام ها
33 | GatewayIntentBits.MessageContent // خواندن محتوای پیام ها
34 | ]
35 | });
36 | ```
37 |
38 | 2. **اتصال با توکن**:
39 |
40 | ```javascript
41 | client.login('TOKEN_ربات_خود');
42 | ```
43 |
44 | 3. **رویداد `ready`**:
45 |
46 | ```javascript
47 | client.on('ready', () => {
48 | console.log(`✅ ${client.user.tag} آنلاین شد!`);
49 | });
50 | ```
51 |
52 | ---
53 |
54 | ### **۴.۴ پاسخ به پیام های کاربران**
55 | از رویداد `messageCreate` برای دریافت پیام ها استفاده می شود:
56 |
57 | ```javascript
58 | client.on('messageCreate', (message) => {
59 | // اگر نویسنده پیام خود ربات باشد، پردازش نکند
60 | if (message.author.bot) return;
61 |
62 | // پاسخ به پیام "سلام"
63 | if (message.content === 'سلام') {
64 | message.reply('سلام! چطوری؟ 😊');
65 | }
66 | });
67 | ```
68 |
69 | ---
70 |
71 | ### **۴.۵ ساخت اولین دستور (پینگ-پونگ)**
72 |
73 | ```javascript
74 | client.on('messageCreate', (message) => {
75 | if (message.content === '!ping') {
76 | const start = Date.now();
77 | message.reply('در حال محاسبه پینگ...').then((sentMessage) => {
78 | const latency = Date.now() - start;
79 | sentMessage.edit(`🏓 پونگ! تاخیر: ${latency}ms`);
80 | });
81 | }
82 | });
83 | ```
84 |
85 | ---
86 |
87 | ### **۴.۶ کار با اطلاعات پیام**
88 | هر شیء `message` شامل اطلاعات مفیدی است:
89 | - **محتوا**: `message.content`
90 | - **نویسنده**: `message.author.tag`
91 | - **کانال**: `message.channel.name`
92 | - **سرور**: `message.guild.name`
93 |
94 | **مثال**:
95 |
96 | ```javascript
97 | client.on('messageCreate', (message) => {
98 | console.log(
99 | `پیام از ${message.author.tag} در کانال #${message.channel.name}: ${message.content}`
100 | );
101 | });
102 | ```
103 |
104 | ---
105 |
106 | ### **تمرین عملی فصل ۴**
107 | ۱. رباتی بسازید که به دستور `!ساعت` زمان فعلی را پاسخ دهد.
108 | ۲. دستوری ایجاد کنید که با `!کاربر` نام و تگ کاربر را برگرداند.
109 | ۳. دستور `!پاککن` را پیاده سازی کنید تا تعداد پیام های مشخصی را پاک کند (اختیاری).
110 |
111 | **مثال تمرین ۱**:
112 |
113 | ```javascript
114 | if (message.content === '!ساعت') {
115 | const time = new Date().toLocaleTimeString('fa-IR');
116 | message.reply(`ساعت فعلی: ${time}`);
117 | }
118 | ```
119 |
120 | ---
121 |
122 | ### **مشکلات رایج و راه حل ها**
123 | - **ربات آنلاین نمی شود**:
124 | - توکن را بررسی کنید.
125 | - اینترنت وصل است؟
126 | - آیا Intentهای لازم در پنل توسعه دهندگان فعال شده اند؟ ([راهنمای فعالسازی Intents](https://discordjs.guide/preparations/setting-up-a-bot-application.html#creating-your-bot))
127 | - **ربات به پیام ها پاسخ نمی دهد**:
128 | - Intent `MessageContent` را اضافه کنید.
129 | - مطمئن شوید ربات به سرور اضافه شده است.
130 |
131 | ---
132 |
133 | ### **نکات کلیدی**
134 | - **Gateway Intents** را در [پنل توسعه دهندگان دیسکورد](https://discord.com/developers/applications) فعال کنید.
135 | - **هرگز توکن ربات را در کد عمومی قرار ندهید** (از فایل `.env` استفاده کنید. فصل ۷ آموزش داده می شود).
136 | - برای دستورات پیشرفته تر، از **Slash Commands** استفاده کنید (فصل ۶).
137 |
138 | ---
139 |
140 | در فصل بعدی، **ساخت دستورات پیشرفته تر** و کار با **Embedها** را یاد خواهید گرفت! 🚀
--------------------------------------------------------------------------------
/javascript/per/saeson5.md:
--------------------------------------------------------------------------------
1 | **فصل ۵: ساخت دستورات پیشرفته تر و کار با Embed ها**
2 |
3 | ---
4 |
5 | ### **۵.۱ پردازش دستورات با پیشوند (Prefix Commands)**
6 | برای ساخت دستورات حرفه ای تر، باید پیام های کاربران را تجزیه و تحلیل کنید.
7 |
8 | #### **مراحل پردازش دستورات**:
9 | ۱. **بررسی پیشوند**:
10 |
11 | ```javascript
12 | const prefix = '!'; // پیشوند دستورات (مثلاً !پینگ)
13 | if (!message.content.startsWith(prefix)) return;
14 | ```
15 |
16 | ۲. **جداسازی دستور و آرگومان ها**:
17 |
18 | ```javascript
19 | const args = message.content.slice(prefix.length).trim().split(/ +/);
20 | const command = args.shift().toLowerCase(); // نام دستور (مثلاً "پینگ")
21 | ```
22 |
23 | **مثال**:
24 |
25 | ```javascript
26 | client.on('messageCreate', (message) => {
27 | if (!message.content.startsWith('!') || message.author.bot) return;
28 |
29 | const args = message.content.slice(1).split(/ +/);
30 | const command = args.shift().toLowerCase();
31 |
32 | if (command === 'ساین') {
33 | const text = args.join(' ');
34 | message.channel.send(`📢 ${text.toUpperCase()}`);
35 | }
36 | });
37 | ```
38 |
39 | ---
40 |
41 | ### **۵.۲ ساخت Embed های زیبا**
42 | Embed ها پیام های ساختار یافته و جذابی هستند که اطلاعات را به صورت سازماندهی شده نمایش می دهند.
43 |
44 | #### **استفاده از `EmbedBuilder`**:
45 |
46 | ```javascript
47 | const { EmbedBuilder } = require('discord.js');
48 |
49 | const exampleEmbed = new EmbedBuilder()
50 | .setColor(0x0099FF) // رنگ نوار کناری (به فرمت HEX)
51 | .setTitle('عنوان Embed')
52 | .setDescription('توضیحات کلی')
53 | .addFields(
54 | { name: 'فیلد ۱', value: 'مقدار ۱', inline: true },
55 | { name: 'فیلد ۲', value: 'مقدار ۲', inline: true },
56 | )
57 | .setImage('https://example.com/image.png')
58 | .setTimestamp(); // اضافه کردن زمان فعلی
59 |
60 | message.channel.send({ embeds: [exampleEmbed] });
61 | ```
62 |
63 | #### **مثال عملی (دستور !کاربر)**:
64 |
65 | ```javascript
66 | if (command === 'کاربر') {
67 | const user = message.author;
68 | const embed = new EmbedBuilder()
69 | .setColor('Random')
70 | .setTitle('اطلاعات کاربر')
71 | .setThumbnail(user.displayAvatarURL())
72 | .addFields(
73 | { name: 'تگ', value: user.tag },
74 | { name: 'آیدی', value: user.id },
75 | { name: 'تاریخ ساخت حساب', value: user.createdAt.toLocaleDateString('fa-IR') }
76 | );
77 |
78 | message.channel.send({ embeds: [embed] });
79 | }
80 | ```
81 |
82 | ---
83 |
84 | ### **۵.۳ دستورات مدیریتی (ادمین)**
85 | ساخت دستوراتی که نیاز به دسترسی های خاص دارند (مثلاً پاک کردن پیام ها).
86 |
87 | #### **دستور !پاککن**:
88 |
89 | ```javascript
90 | if (command === 'پاککن') {
91 | // بررسی آیا کاربر دارای دسترسی مدیریت پیام ها است
92 | if (!message.member.permissions.has('ManageMessages')) {
93 | return message.reply('❌ شما دسترسی لازم را ندارید!');
94 | }
95 |
96 | const amount = parseInt(args[0]) || 10; // پیشفرض ۱۰ پیام
97 | if (isNaN(amount) || amount > 100) {
98 | return message.reply('لطفاً عددی بین ۱ تا ۱۰۰ وارد کنید!');
99 | }
100 |
101 | message.channel.bulkDelete(amount + 1) // +1 برای حذف خود دستور
102 | .then(() => {
103 | message.channel.send(`✅ ${amount} پیام پاک شد!`).then(msg => {
104 | setTimeout(() => msg.delete(), 5000);
105 | });
106 | })
107 | .catch(console.error);
108 | }
109 | ```
110 |
111 | ---
112 |
113 | ### **۵.۴ افزودن Reactions به پیام ها**
114 | استفاده از ری اکشن ها برای تعامل بیشتر (مثلاً نظرسنجی).
115 |
116 | **مثال (دستور !نظرسنجی)**:
117 |
118 | ```javascript
119 | if (command === 'نظرسنجی') {
120 | const question = args.join(' ');
121 | if (!question) return message.reply('لطفاً سوال نظرسنجی را وارد کنید!');
122 |
123 | const pollEmbed = new EmbedBuilder()
124 | .setColor('#FFD700')
125 | .setTitle('📊 نظرسنجی')
126 | .setDescription(question)
127 | .addFields({ name: 'دستورالعمل', value: 'با ✅/❌ رأی دهید!' });
128 |
129 | message.channel.send({ embeds: [pollEmbed] }).then(pollMessage => {
130 | pollMessage.react('✅');
131 | pollMessage.react('❌');
132 | });
133 | }
134 | ```
135 |
136 | ---
137 |
138 | ### **تمرین عملی فصل ۵**
139 | ۱. دستوری بسازید که با `!سطح` اطلاعات سطح کاربر (XP) را در Embed نمایش دهد (داده ها را می توانید در آرایه ذخیره کنید).
140 | ۲. دستور `!کمک` ایجاد کنید که لیست دستورات ربات را در یک Embed سازماندهی کند.
141 | ۳. دستور `!بن` را پیاده سازی کنید که کاربران را با آیدی بن کند (اختیاری).
142 |
143 | ---
144 |
145 | ### **مشکلات رایج و راه حل ها**
146 | - **Embed ارسال نمی شود**:
147 | - مطمئن شوید از `embeds: [embed]` استفاده کرده اید نه `embed: embed`.
148 | - بررسی کنید رنگ (Color) را بهدرستی تنظیم کرده اید.
149 | - **خطای دسترسی (Permissions)**:
150 | - در پنل دیسکورد، دسترسی **Manage Messages** را به ربات بدهید.
151 | - از `message.member.permissions.has()` برای بررسی دسترسی کاربر استفاده کنید.
152 |
153 | ---
154 |
155 | ### **نکات کلیدی**
156 | - برای جلوگیری از Overwrite شدن Embedها، هر فیلد نباید بیش از **1024 کاراکتر** باشد.
157 | - از `setFooter()` برای افزودن متن پایینی در Embed استفاده کنید.
158 | - برای دریافت اطلاعات سرور (Guild) از `message.guild` استفاده کنید.
159 |
160 | ---
161 |
162 | در فصل بعدی، **مفاهیم پیشرفته تر** مثل **Slash Commands**، **مدیریت خطا ها** و **کار با دیتابیس** را یاد خواهید گرفت! 🚀
--------------------------------------------------------------------------------
/javascript/per/saeson6.md:
--------------------------------------------------------------------------------
1 | **فصل ۶: مفاهیم پیشرفته تر**
2 |
3 | ---
4 |
5 | ### **۶.۱ مدیریت خطا ها (Error Handling)**
6 | هر ربات ممکن است با خطا مواجه شود! مدیریت خطا باعث می شود ربات شما به جای کرش کردن، به کار خود ادامه دهد.
7 |
8 | #### **استفاده از `try/catch`**
9 |
10 | ```javascript
11 | client.on('messageCreate', async (message) => {
12 | try {
13 | // کدی که ممکن است خطا دهد (مثلاً دسترسی به API)
14 | await someRiskyOperation();
15 | } catch (error) {
16 | console.error('خطا رخ داد:', error);
17 | message.reply('⚠️ خطایی رخ داد! لطفاً بعداً تلاش کنید.');
18 | }
19 | });
20 | ```
21 |
22 | #### **لاگ گیری از خطا ها**
23 | - خطا ها را در فایل ذخیره کنید:
24 |
25 | ```javascript
26 | const fs = require('fs');
27 | fs.appendFileSync('errors.log', `${new Date().toISOString()}: ${error.stack}\n`);
28 | ```
29 |
30 | ---
31 |
32 | ### **۶.۲ دستورات اسلشی (Slash Commands)**
33 | دستورات اسلشی (/command) تجربه کاربری بهتری دارند و نیاز به پیشوند (!) ندارند.
34 |
35 | #### **ثبت دستورات اسلشی**
36 | ۱. **تعریف دستور در کد**:
37 |
38 | ```javascript
39 | const { SlashCommandBuilder } = require('discord.js');
40 |
41 | module.exports = {
42 | data: new SlashCommandBuilder()
43 | .setName('پینگ')
44 | .setDescription('پینگ ربات را بررسی کنید'),
45 | async execute(interaction) {
46 | await interaction.reply('🏓 پونگ!');
47 | }
48 | };
49 | ```
50 |
51 | ۲. **ثبت دستورات در دیسکورد**:
52 | - برای **یک سرور خاص** (سریعتر):
53 |
54 | ```javascript
55 | const rest = new REST().setToken(process.env.TOKEN);
56 | const commands = [پینگCommand.data.toJSON()];
57 | await rest.put(
58 | Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID),
59 | { body: commands }
60 | );
61 | ```
62 | - برای **همه سرور ها** (Global):
63 | ```javascript
64 | await rest.put(Routes.applicationCommands(CLIENT_ID), { body: commands });
65 | ```
66 |
67 | ---
68 |
69 | ### **۶.۳ کار با دیتابیس**
70 | برای ذخیره داده های پایدار (مثل XP کاربران) نیاز به دیتابیس دارید.
71 |
72 | #### **استفاده از JSON فایل (ساده)**
73 |
74 | ```javascript
75 | const fs = require('fs');
76 |
77 | // خواندن دیتابیس
78 | let db = JSON.parse(fs.readFileSync('database.json'));
79 |
80 | // ذخیره XP کاربر
81 | db[message.author.id] = { xp: 100, level: 2 };
82 |
83 | // آپدیت فایل
84 | fs.writeFileSync('database.json', JSON.stringify(db));
85 | ```
86 |
87 | #### **استفاده از SQLite (پیشرفته تر)**
88 | ۱. نصب پکیج:
89 | ```bash
90 | npm install better-sqlite3
91 | ```
92 |
93 | ۲. اتصال به دیتابیس:
94 |
95 | ```javascript
96 | const Database = require('better-sqlite3');
97 | const db = new Database('database.sqlite');
98 |
99 | // ساخت جدول
100 | db.prepare(`
101 | CREATE TABLE IF NOT EXISTS users (
102 | id TEXT PRIMARY KEY,
103 | xp INTEGER DEFAULT 0,
104 | level INTEGER DEFAULT 1
105 | )
106 | `).run();
107 | ```
108 |
109 | ۳. افزودن داده:
110 | ```javascript
111 | const insert = db.prepare('INSERT INTO users (id, xp) VALUES (?, ?)');
112 | insert.run(message.author.id, 100);
113 | ```
114 |
115 | ---
116 |
117 | ### **۶.۴ سیستم لول (XP System)**
118 | **مثال عملی با JSON**:
119 |
120 | ```javascript
121 | client.on('messageCreate', (message) => {
122 | if (message.author.bot) return;
123 |
124 | // افزایش XP کاربر
125 | const userId = message.author.id;
126 | db[userId] = db[userId] || { xp: 0, level: 1 };
127 | db[userId].xp += 10;
128 |
129 | // بررسی ارتقا سطح
130 | if (db[userId].xp >= db[userId].level * 100) {
131 | db[userId].level += 1;
132 | message.channel.send(`🎉 ${message.author} به سطح ${db[userId].level} رسید!`);
133 | }
134 |
135 | fs.writeFileSync('database.json', JSON.stringify(db));
136 | });
137 | ```
138 |
139 | ---
140 |
141 | ### **تمرین عملی فصل ۶**
142 | ۱. دستور اسلشی `/ساعت` بسازید که زمان فعلی را برگرداند.
143 | ۲. با SQLite جدولی برای نظرسنجی ها ایجاد کنید و نتایج را ذخیره کنید.
144 | ۳. سیستمی طراحی کنید که با هر پیام کاربر، شانس تصادفی جایزه بدهد!
145 |
146 | ---
147 |
148 | ### **مشکلات رایج و راه حل ها**
149 | - **دستورات اسلشی نمایش داده نمی شوند**:
150 | - ۲۴-۴۸ ساعت صبر کنید (برای دستورات Global).
151 | - از `CLIENT_ID` و `GUILD_ID` معتبر استفاده کنید.
152 | - **خطای دسترسی دیتابیس**:
153 | - مطمئن شوید فایل های JSON/SQLite قابل نوشتن هستند.
154 | - از مسیر های نسبی (مثل `./database.json`) استفاده کنید.
155 |
156 | ---
157 |
158 | ### **نکات کلیدی**
159 | - برای محیط Production از دیتابیس های قویتر مثل **PostgreSQL** یا **MongoDB** استفاده کنید.
160 | - همیشه قبل از تعامل با دیتابیس، ورودی کاربر را **اعتبارسنجی** کنید (برای جلوگیری از حمله تزریق SQL).
161 | - از **.env** برای ذخیره توکن و اطلاعات حساس استفاده کنید (فصل ۷).
162 |
163 | ---
164 |
165 | در فصل بعدی، **استقرار (Deploy) ربات** روی سرور و نکات امنیتی را یاد خواهید گرفت! 🚀
--------------------------------------------------------------------------------
/javascript/per/saeson7.md:
--------------------------------------------------------------------------------
1 | **فصل ۷: استقرار (Deploy)، نگه داری و امنیت ربات**
2 |
3 | ---
4 |
5 | ### **۷.۱ آماده سازی ربات برای استقرار**
6 | قبل از آپلود ربات روی سرور، باید مطمئن شوید:
7 | 1. **پنهان کردن توکن و اطلاعات حساس**:
8 | - از پکیج `dotenv` برای استفاده از فایل `.env` استفاده کنید.
9 | - فایل `.env`:
10 | ```env
11 | TOKEN=مقدار_توکن_شما
12 | PREFIX=!
13 | ```
14 | - در کد:
15 | ```javascript
16 | require('dotenv').config();
17 | client.login(process.env.TOKEN);
18 | ```
19 |
20 | 2. **حذف فایل های غیرضروری**:
21 | - فایل `node_modules` را با دستور `npm install --production` دوباره نصب کنید.
22 | - فایل های تست و لوکال (`database.json` یا ...) را بررسی کنید.
23 |
24 | ---
25 |
26 | ### **۷.۲ استقرار روی سرور های ابری (رایگان)**
27 | #### **روش ۱: استفاده از Replit**
28 | - مناسب برای شروع و پروژه های کوچک.
29 | 1. پروژه جدید در [Replit](https://replit.com) بسازید.
30 | 2. کدها را آپلود کنید و فایل `.env` را در **Secrets** قرار دهید.
31 | 3. از **Always On** استفاده کنید تا ربات ۲۴/۷ فعال بماند.
32 |
33 | #### **روش ۲: استفاده از Railway یا Heroku**
34 | - **Railway** (رایگان با محدودیت):
35 | 1. پروژه را به GitHub متصل کنید.
36 | 2. متغیر های محیطی (Environment Variables) را در تنظیمات اضافه کنید.
37 | 3. دامنه رایگان Railway را استفاده کنید.
38 |
39 | ---
40 |
41 | ### **۷.۳ استقرار روی سرور اختصاصی (VPS)**
42 | #### **مراحل پایه برای لینوکس (Ubuntu)**:
43 | 1. **اتصال به سرور**:
44 | ```bash
45 | ssh root@IP_سرور
46 | ```
47 |
48 | 2. **نصب Node.js و npm**:
49 | ```bash
50 | curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
51 | sudo apt-get install -y nodejs
52 | ```
53 |
54 | 3. **کپی کردن فایل های پروژه**:
55 |
56 | ```bash
57 | git clone https://github.com/نام-کاربری/ربات-شما.git
58 | cd ربات-شما
59 | npm install
60 | ```
61 |
62 | 4. **اجرای ربات با PM2 (برای اجرای دائمی)**:
63 | ```bash
64 | sudo npm install -g pm2
65 | pm2 start index.js --name "my-bot"
66 | pm2 save
67 | pm2 startup
68 | ```
69 |
70 | ---
71 |
72 | ### **۷.۴ امنیت ربات**
73 | 1. **محدود کردن دسترسی ها**:
74 | - در پنل توسعه دهندگان دیسکورد، فقط **Intents** لازم را فعال کنید.
75 | - از دسترسی های ربات (**Bot Permissions**) به صورت دقیق استفاده کنید (مثلاً فقط `Send Messages` و `Read Message History`).
76 |
77 | 2. **جلوگیری از حمله DDoS یا اسپم**:
78 | - محدودیت نرخ (Rate Limiting) با پکیج `express-rate-limit`.
79 | - بررسی کد برای حلقه های بینهایت.
80 |
81 | 3. **بکاپ گیری منظم**:
82 | - از دیتابیس و فایل های مهم به صورت خودکار بکاپ بگیرید (مثلاً با Cron Jobs).
83 |
84 | ---
85 |
86 | ### **۷.۵ نگه داری و بهینهسازی**
87 | 1. **مانیتورینگ منابع**:
88 | - با `pm2 list` وضعیت ربات را بررسی کنید.
89 | - از `pm2 logs` برای مشاهده لاگ ها استفاده کنید.
90 |
91 | 2. **بروزرسانی پکیج ها**:
92 | ```bash
93 | npm outdated # بررسی پکیج های قدیمی
94 | npm update # بروزرسانی
95 | ```
96 |
97 | 3. **مدیریت خطا های غیرمنتظره**:
98 | - از `process.on('uncaughtException')` برای جلوگیری از کرش استفاده کنید:
99 | ```javascript
100 | process.on('uncaughtException', (error) => {
101 | console.error('خطای کشف نشده:', error);
102 | });
103 | ```
104 |
105 | ---
106 |
107 | ### **تمرین عملی فصل ۷**
108 | ۱. ربات خود را روی Replit یا Railway مستقر کنید و مطمئن شوید ۲۴/۷ فعال است.
109 | ۲. با PM2 ربات را روی یک سرور لینوکس (حتی لوکال) اجرا کنید.
110 | ۳. یک سیستم بکاپ گیری ساده با Cron Job برای دیتابیس بسازید.
111 |
112 | ---
113 |
114 | ### **مشکلات رایج**
115 | - **ربات بعد از مدتی قطع می شود**:
116 | - از PM2 یا Docker برای اجرای دائمی استفاده کنید.
117 | - منابع سرور (CPU/RAM) را بررسی کنید.
118 | - **خطای `Missing Permissions`**:
119 | - دسترسی های ربات را در [پنل دیسکورد](https://discord.com/developers/applications) بررسی کنید.
120 |
121 | ---
122 |
123 | ### **نکات طلایی**
124 | - برای پروژه های بزرگ، از **Docker** استفاده کنید تا محیط اجرا یکسان بماند.
125 | - همیشه **ورژن های اصلی** (Major Versions) کتابخانه ها را بررسی کنید (مثلاً تغییرات discord.js v13 به v14).
126 | - در صورت امکان، از **Webhooks** برای دریافت نوتیفیکیشن خطا ها استفاده کنید.
127 |
128 | ---
129 |
130 | با پایان این فصل، شما توانایی ساخت، استقرار و نگه داری یک ربات حرفه ای دیسکورد را دارید! 🎉
131 | **[پیشنهاد]** در فصل بعدی، چند پروژه عملی برای تثبیت مهارت ها انجام خواهیم داد!
--------------------------------------------------------------------------------
/javascript/per/saeson8.md:
--------------------------------------------------------------------------------
1 | **فصل ۸: پروژه های عملی برای تثبیت مهارت ها**
2 |
3 | ---
4 |
5 | ### **۸.۱ پروژه ۱: ربات نظرسنجی (Poll Bot)**
6 | **هدف**: ساخت رباتی که با دستور `!نظرسنجی [سوال]` یک نظرسنجی با Reactions ایجاد کند و نتایج را تحلیل کند.
7 |
8 | #### **مراحل پیاده سازی**:
9 | ۱. **دریافت سوال و ایجاد Embed**:
10 |
11 | ```javascript
12 | client.on('messageCreate', async (message) => {
13 | if (!message.content.startsWith('!نظرسنجی') || message.author.bot) return;
14 | const question = message.content.slice(9).trim();
15 | if (!question) return message.reply('لطفاً سوال نظرسنجی را وارد کنید!');
16 |
17 | const pollEmbed = new EmbedBuilder()
18 | .setColor('#5865F2')
19 | .setTitle('📊 نظرسنجی جدید')
20 | .setDescription(question)
21 | .addFields({ name: 'گزینه ها', value: '✅ = موافق\n❌ = مخالف' });
22 |
23 | const pollMessage = await message.channel.send({ embeds: [pollEmbed] });
24 | await pollMessage.react('✅');
25 | await pollMessage.react('❌');
26 | });
27 | ```
28 |
29 | ۲. **جمع آوری نتایج**:
30 |
31 | ```javascript
32 | client.on('messageReactionAdd', async (reaction, user) => {
33 | if (user.bot) return;
34 | if (reaction.message.embeds[0]?.title === '📊 نظرسنجی جدید') {
35 | const agree = reaction.message.reactions.cache.get('✅')?.count || 0;
36 | const disagree = reaction.message.reactions.cache.get('❌')?.count || 0;
37 | // ذخیره نتایج در دیتابیس یا نمایش آن
38 | }
39 | });
40 | ```
41 |
42 | ---
43 |
44 | ### **۸.۲ پروژه ۲: ربات پخش موزیک (Music Bot)**
45 | **هدف**: ساخت رباتی که به کانال صوتی متصل شود و آهنگ پخش کند.
46 |
47 | #### **مراحل پیاده سازی**:
48 | ۱. **نصب پکیج های مورد نیاز**:
49 | ```bash
50 | npm install @discordjs/voice @discordjs/rest @discordjs/opus ffmpeg-static ytdl-core
51 | ```
52 |
53 | ۲. **اتصال به کانال صوتی**:
54 |
55 | ```javascript
56 | const { joinVoiceChannel, createAudioPlayer, createAudioResource } = require('@discordjs/voice');
57 |
58 | client.on('messageCreate', async (message) => {
59 | if (message.content.startsWith('!پخش')) {
60 | const voiceChannel = message.member.voice.channel;
61 | if (!voiceChannel) return message.reply('⚠️ اول به کانال صوتی جوین شو!');
62 |
63 | const connection = joinVoiceChannel({
64 | channelId: voiceChannel.id,
65 | guildId: voiceChannel.guild.id,
66 | adapterCreator: voiceChannel.guild.voiceAdapterCreator,
67 | });
68 |
69 | const stream = ytdl('https://youtu.be/آیدی-آهنگ', { filter: 'audioonly' });
70 | const resource = createAudioResource(stream);
71 | const player = createAudioPlayer();
72 |
73 | connection.subscribe(player);
74 | player.play(resource);
75 | }
76 | });
77 | ```
78 |
79 | ---
80 |
81 | ### **۸.۳ پروژه ۳: سیستم سطح بندی (XP System)**
82 | **هدف**: ساخت سیستمی که فعالیت کاربران را ردیابی کند و بر اساس XP به آن ها سطح دهد.
83 |
84 | #### **مراحل پیاده سازی**:
85 | ۱. **ذخیره داده ها در JSON**:
86 |
87 | ```javascript
88 | const fs = require('fs');
89 | let xpData = JSON.parse(fs.readFileSync('xp.json', 'utf8')) || {};
90 |
91 | client.on('messageCreate', (message) => {
92 | if (message.author.bot) return;
93 |
94 | const userId = message.author.id;
95 | xpData[userId] = xpData[userId] || { xp: 0, level: 1 };
96 |
97 | // افزایش XP تصادفی بین ۵ تا ۱۵
98 | xpData[userId].xp += Math.floor(Math.random() * 11) + 5;
99 |
100 | // بررسی ارتقا سطح
101 | const xpRequired = xpData[userId].level * 100;
102 | if (xpData[userId].xp >= xpRequired) {
103 | xpData[userId].level += 1;
104 | message.channel.send(`🎉 ${message.author} به سطح ${xpData[userId].level} رسید!`);
105 | }
106 |
107 | fs.writeFileSync('xp.json', JSON.stringify(xpData));
108 | });
109 | ```
110 |
111 | ۲. **دستور !سطح**:
112 |
113 | ```javascript
114 | if (message.content === '!سطح') {
115 | const userData = xpData[message.author.id] || { xp: 0, level: 1 };
116 | const embed = new EmbedBuilder()
117 | .setTitle('📊 سطح شما')
118 | .addFields(
119 | { name: 'سطح', value: userData.level.toString() },
120 | { name: 'XP', value: userData.xp.toString() }
121 | );
122 | message.channel.send({ embeds: [embed] });
123 | }
124 | ```
125 |
126 | ---
127 |
128 | ### **۸.۴ پروژه ۴: ربات مُدیریتی (Moderation Bot)**
129 | **هدف**: ساخت رباتی با دستورات مدیریتی مثل بن، میوت و پاک کردن پیام.
130 |
131 | #### **دستور !بن**:
132 | ```javascript
133 | if (command === 'بن') {
134 | if (!message.member.permissions.has('BanMembers')) {
135 | return message.reply('❌ شما دسترسی بن کردن ندارید!');
136 | }
137 |
138 | const target = message.mentions.users.first();
139 | if (!target) return message.reply('⚠️ کاربر را منشن کنید!');
140 |
141 | message.guild.members.ban(target.id)
142 | .then(() => message.reply(`✅ ${target.tag} بن شد!`))
143 | .catch(() => message.reply('⛔ خطا در بن کردن!'));
144 | }
145 | ```
146 |
147 | ---
148 |
149 | ### **۸.۵ پروژه ۵: ربات مینی گیم (سکه، شانس، ...)**
150 | **هدف**: ساخت بازی های ساده برای تعامل با کاربران.
151 |
152 | #### **دستور !سکه**:
153 | ```javascript
154 | if (command === 'سکه') {
155 | const result = Math.random() < 0.5 ? 'رو' : 'پشت';
156 | message.reply(`سکه انداختم... **${result}** آمد!`);
157 | }
158 |
159 | // دستور !شماره
160 | if (command === 'شماره') {
161 | const number = Math.floor(Math.random() * 100) + 1;
162 | message.reply(`شماره تصادفی: **${number}**`);
163 | }
164 | ```
165 |
166 | ---
167 |
168 | ### **تمرین های تکمیلی**:
169 | ۱. **ربات تیکت**: سیستمی که با دستور `!تیکت` یک کانال جدید برای کاربر ایجاد کند.
170 | ۲. **ربات واژه یاب**: با دستور `!معنی [کلمه]` معنی کلمه را از یک API دریافت کند.
171 | ۳. **ربات آب وهوا**: با دستور `!آبوهوا [شهر]` اطلاعات آب وهوا را نمایش دهد.
172 |
173 | ---
174 |
175 | ### **مشکلات رایج**:
176 | - **ربات موزیک صدا پخش نمی کند**:
177 | - مطمئن شوید **FFmpeg** نصب است (`npm install ffmpeg-static`).
178 | - بررسی کنید ربات به کانال صوتی وارد شده است.
179 | - **سیستم XP داده ها را ذخیره نمی کند**:
180 | - از `fs.writeFileSync` بعد از هر تغییر استفاده کنید.
181 | - مسیر فایل `xp.json` را بررسی کنید.
182 |
183 | ---
184 |
185 | ### **نکات نهایی**:
186 | - پروژه ها را به صورت **ماژولار** کد نویسی کنید (هر دستور در فایل جداگانه).
187 | - از **GitHub** برای مدیریت نسخه ها استفاده کنید.
188 | - برای ایدههای بیشتر، به [Discord Bot Ideas](https://github.com/discordjs/guide/discussions) مراجعه کنید.
189 |
190 | ---
191 |
192 | **پایان دوره!** 🎓
193 | حالا شما می توانید ربات های دیسکورد حرفه ای بسازید، آن ها را توسعه دهید و روی سرور منتشر کنید. یادگیری را ادامه دهید و پروژه های شخصی سازی شده خود را خلق کنید!
--------------------------------------------------------------------------------
/python/en/README.md:
--------------------------------------------------------------------------------
1 | # Table of Contents
2 |
3 | ### [**Chapter 1: Introduction and Environment Setup**](./saeson1.md)
4 |
5 | 1. **What Is Programming?**
6 |
7 | * Why Discord and Python?
8 | * Use cases for Discord bots.
9 | 2. **Required Tools**
10 |
11 | * Installing Python and pip.
12 | * Choosing a code editor (e.g., VS Code or PyCharm).
13 | * Creating your bot in the Discord Developer Portal.
14 | * Obtaining your bot token.
15 |
16 | ---
17 |
18 | ### [**Chapter 2: Python Fundamentals**](./saeson2.md)
19 |
20 | 1. **Variables and Data Types**
21 |
22 | * Strings, numbers, booleans, lists, dictionaries.
23 | 2. **Operators and Control Flow**
24 |
25 | * Arithmetic, comparison, and logical operators.
26 | * Conditional statements (`if` / `elif` / `else`).
27 | * Loops (`for`, `while`).
28 | 3. **Functions and Modules**
29 |
30 | * Defining functions.
31 | * Function inputs and outputs.
32 | * Using `import` and creating custom modules.
33 |
34 | ---
35 |
36 | ### [**Chapter 3: Getting Started with discord.py**](./saeson3.md)
37 |
38 | 1. **Installation and Setup**
39 |
40 | * Installing the library with `pip install discord.py`.
41 | * Differences between `discord.py` and `nextcord`.
42 | 2. **Bot Structure**
43 |
44 | * The `Bot` class and `Intents`.
45 | * Core events (`on_ready`, `on_message`).
46 |
47 | ---
48 |
49 | ### [**Chapter 4: Building Your First Bot**](./saeson4.md)
50 |
51 | 1. **Connecting to Discord**
52 |
53 | * Using the token and running the bot.
54 | 2. **Responding to Messages**
55 |
56 | * Handling user messages with `on_message`.
57 | * Ignoring other bots.
58 | 3. **Creating Simple Commands**
59 |
60 | * Using a prefix (e.g., `!ping`).
61 |
62 | ---
63 |
64 | ### [**Chapter 5: Working with Embeds and Files**](./saeson5.md)
65 |
66 | 1. **Creating Rich Embeds**
67 |
68 | * Using the `Embed` class.
69 | * Adding fields, images, and footers.
70 | 2. **Sending and Receiving Files**
71 |
72 | * Uploading attachments to Discord.
73 | * Downloading files from messages.
74 |
75 | ---
76 |
77 | ### [**Chapter 6: Advanced Commands (Cogs and Commands)**](./saeson6.md)
78 |
79 | 1. **Defining Commands with `@commands.command`**
80 |
81 | * Creating prefixed commands.
82 | * Error handling with `@commands.errors`.
83 | 2. **Organizing Code with Cogs**
84 |
85 | * Building Cog classes.
86 | * Adding Cogs to your bot.
87 |
88 | ---
89 |
90 | ### [**Chapter 7: Slash Commands**](./saeson7.md)
91 |
92 | 1. **Registering Slash Commands**
93 |
94 | * Using `@slash_command`.
95 | * Syncing commands with Discord.
96 | 2. **Command Parameters**
97 |
98 | * Accepting user input (text, numbers, users).
99 |
100 | ---
101 |
102 | ### [**Chapter 8: Database Integration**](./saeson8.md)
103 |
104 | 1. **Storing Data in JSON**
105 |
106 | * Reading from and writing to JSON files.
107 | 2. **Using SQLite**
108 |
109 | * Connecting to the database and running queries.
110 | 3. **XP Leveling System**
111 |
112 | * Tracking user activity and storing progress.
113 |
114 | ---
115 |
116 | ### [**Chapter 9: Server and User Management**](./saeson9.md)
117 |
118 | 1. **Moderation Commands**
119 |
120 | * Ban, mute, bulk delete.
121 | 2. **Working with Roles**
122 |
123 | * Creating, editing, and assigning roles.
124 |
125 | ---
126 |
127 | ### [**Chapter 10: Deployment**](./saeson10.md)
128 |
129 | 1. **Deploying to Cloud Platforms**
130 |
131 | * Using Replit, Heroku, or Railway.
132 | 2. **Running on a Linux Server**
133 |
134 | * Managing with PM2 or systemd.
135 | 3. **Security and Maintenance**
136 |
137 | * Hiding tokens with `.env`.
138 | * Keeping libraries up to date.
139 |
140 | ---
141 |
142 | ### [**Chapter 11: Practical Projects**](./saeson11.md)
143 |
144 | 1. **Poll Bot**
145 |
146 | * Reactions-based voting and result analysis.
147 | 2. **Music Bot**
148 |
149 | * Joining a voice channel and playing audio.
150 | 3. **Mini-Games Bot**
151 |
152 | * Simple games like coin flip, random quiz, and rewards.
153 |
154 | ---
155 |
156 | ### **Appendices & Further Resources**
157 |
158 | * Official [discord.py Documentation](https://discordpy.readthedocs.io/)
159 | * GitHub repo with example code snippets.
160 | * Support communities (Discord servers, Stack Overflow).
161 |
162 | ---
163 |
164 | ### **Key Teaching Guidelines**
165 |
166 | * Introduce each chapter with concise, example-driven explanations.
167 | * Use diagrams and screenshots to clarify complex concepts.
168 | * Provide hands-on exercises at the end of each lesson.
169 | * Emphasize debugging techniques and troubleshooting common errors.
--------------------------------------------------------------------------------
/python/en/saeson1.md:
--------------------------------------------------------------------------------
1 | ## Chapter 1: Introduction and Setting Up Your Environment
2 |
3 | ---
4 |
5 | ### 1.1 What Is Programming?
6 |
7 | Programming means writing instructions that a computer can execute to produce a specific output or behavior.
8 |
9 | * **Why Discord and Python?**
10 |
11 | * **Discord** is a popular platform for online communities and supports creating automated bots.
12 | * **Python** is a simple yet powerful language with excellent libraries—like `discord.py`—for building Discord bots.
13 |
14 | ---
15 |
16 | ### 1.2 Required Tools
17 |
18 | To get started, you’ll need the following:
19 |
20 | #### 1.2.1 Installing Python and pip
21 |
22 | 1. Visit [Python.org](https://www.python.org).
23 | 2. Download and install **Python 3.10 or newer**.
24 | 3. During installation, enable **Add Python to PATH**.
25 | 4. After installation, open your terminal (or CMD) and verify:
26 |
27 | ```bash
28 | python --version # e.g., Python 3.10.6
29 | pip --version # e.g., pip 23.1.2
30 | ```
31 |
32 | #### 1.2.2 Code Editor: VS Code
33 |
34 | * Download and install VS Code from [here](https://code.visualstudio.com).
35 | * In VS Code’s Extensions panel, install the **Python** extension.
36 |
37 | #### 1.2.3 Creating Your Bot on Discord
38 |
39 | 1. Open the [Discord Developer Portal](https://discord.com/developers/applications).
40 | 2. Click **New Application**, give it a name, and create it.
41 | 3. In the left menu, select **Bot** and click **Add Bot**.
42 | 4. Copy your bot’s **Token** and keep it somewhere safe (e.g., a temporary text file).
43 |
44 | 
45 | 
46 | 
47 | 
48 | 
49 | 
50 | 
51 | 
52 | 
53 |
54 | ---
55 |
56 | ### 1.3 Installing `discord.py`
57 |
58 | In your terminal or CMD, run:
59 |
60 | ```bash
61 | pip install discord.py
62 | ```
63 |
64 | #### Difference Between `discord.py` and `nextcord`
65 |
66 | * `nextcord` is a more up-to-date fork of `discord.py` that fixes many issues. To install it instead, run:
67 |
68 | ```bash
69 | pip install nextcord
70 | ```
71 |
72 | ---
73 |
74 | ### 1.4 Building Your First Bot
75 |
76 | Create a file named `bot.py` and paste in this code:
77 |
78 | ```python
79 | import discord
80 | from discord.ext import commands
81 |
82 | # Basic settings
83 | intents = discord.Intents.default()
84 | intents.message_content = True # Enable reading message content
85 |
86 | bot = commands.Bot(command_prefix='!', intents=intents)
87 |
88 | # Event: bot is ready
89 | @bot.event
90 | async def on_ready():
91 | print(f'✅ Bot {bot.user.name} is now online!')
92 |
93 | # Simple ping command
94 | @bot.command()
95 | async def ping(ctx):
96 | await ctx.reply(f'🏓 Pong! Latency: {round(bot.latency * 1000)}ms')
97 |
98 | # Run the bot
99 | bot.run('YOUR_TOKEN_HERE')
100 | ```
101 |
102 | ---
103 |
104 | ### 1.5 Testing Your Bot
105 |
106 | 1. Replace `'YOUR_TOKEN_HERE'` with your actual token.
107 | 2. Run the bot:
108 |
109 | ```bash
110 | python bot.py
111 | ```
112 | 3. If everything is correct, you’ll see the “online” message in your console.
113 | 4. In Discord, type `!ping` in any server channel to see the bot respond.
114 |
115 | ---
116 |
117 | ### Hands-On Exercise for Chapter 1
118 |
119 | 1. Create your own Discord bot and obtain its token.
120 | 2. Run the code above and verify it replies to `!ping`.
121 | 3. Add a new command—e.g., `!hello`—that sends a greeting back to the user.
122 |
123 | ---
124 |
125 | ### Common Issues
126 |
127 | * **Bot Doesn’t Go Online**
128 |
129 | * Verify your token is correct.
130 | * Check your internet connection.
131 | * Ensure `discord.py` is properly installed.
132 | * **Bot Doesn’t Respond to Messages**
133 |
134 | * Enable `Intents.message_content`.
135 | * Confirm the bot has been invited to your server.
136 |
137 | ---
138 |
139 | ### Key Tips
140 |
141 | * **Never** expose your bot token publicly. (We’ll cover using `.env` files in later chapters.)
142 | * For more advanced commands and organization, use the `discord.ext.commands` module.
143 |
144 | ---
145 |
146 | **Next Chapter:** Python Basics—variables, conditionals, loops, and functions! 🐍
--------------------------------------------------------------------------------
/python/en/saeson10.md:
--------------------------------------------------------------------------------
1 | ## Chapter 10: Deploying Your Bot
2 |
3 | ---
4 |
5 | ### 10.1 Choosing a Deployment Platform
6 |
7 | Selecting the right platform depends on your project’s needs:
8 |
9 | * **Free Cloud Services:** Replit, Railway, Heroku (great for small projects).
10 | * **Virtual Private Servers (VPS):** DigitalOcean, AWS, Hetzner (for professional bots).
11 | * **Local Hosting:** Run on your own computer with tools like PM2 (suitable for testing).
12 |
13 | ---
14 |
15 | ### 10.2 Deploying on Replit (Easiest Method)
16 |
17 | #### Steps:
18 |
19 | 1. Create a new project on [Replit](https://replit.com).
20 | 2. Upload your project files (`main.py`, `requirements.txt`, etc.).
21 | 3. Add your bot token under **Secrets** (Environment Variables).
22 | 4. Include a `keep_alive.py` to prevent the REPL from sleeping:
23 |
24 | ```python
25 | from flask import Flask
26 | from threading import Thread
27 |
28 | app = Flask('')
29 |
30 | @app.route('/')
31 | def home():
32 | return "Bot is alive!"
33 |
34 | def run():
35 | app.run(host='0.0.0.0', port=8080)
36 |
37 | def keep_alive():
38 | t = Thread(target=run)
39 | t.start()
40 | ```
41 | 5. In your main file, call `keep_alive()` before running:
42 |
43 | ```python
44 | keep_alive()
45 | bot.run(os.environ['TOKEN'])
46 | ```
47 |
48 | ---
49 |
50 | ### 10.3 Deploying on a Linux VPS
51 |
52 | #### Ubuntu Basics:
53 |
54 | 1. **SSH into the Server:**
55 |
56 | ```bash
57 | ssh root@YOUR_SERVER_IP
58 | ```
59 | 2. **Install Prerequisites:**
60 |
61 | ```bash
62 | sudo apt update && sudo apt upgrade -y
63 | sudo apt install python3-pip python3-venv git -y
64 | ```
65 | 3. **Clone Your Project:**
66 |
67 | ```bash
68 | git clone https://github.com/your-username/your-bot.git
69 | cd your-bot
70 | ```
71 | 4. **Set Up Virtual Environment & Install Dependencies:**
72 |
73 | ```bash
74 | python3 -m venv venv
75 | source venv/bin/activate
76 | pip install -r requirements.txt
77 | ```
78 | 5. **Use PM2 to Keep It Running:**
79 |
80 | ```bash
81 | npm install pm2 -g
82 | pm2 start "python3 main.py" --name "my-bot"
83 | pm2 save
84 | pm2 startup # generates startup script
85 | ```
86 |
87 | ---
88 |
89 | ### 10.4 Deploying on Railway or Heroku
90 |
91 | #### Railway:
92 |
93 | 1. Create a new project and link your GitHub repo.
94 | 2. Set environment variables under the **Variables** tab.
95 | 3. Specify the default port (e.g., `8000`) and enable **Deploy**.
96 |
97 | #### Heroku:
98 |
99 | 1. Create a new app on [Heroku](https://heroku.com).
100 | 2. Set the Python buildpack:
101 |
102 | ```bash
103 | heroku buildpacks:set heroku/python
104 | ```
105 | 3. Add a `Procfile`:
106 |
107 | ```
108 | worker: python3 main.py
109 | ```
110 | 4. Deploy via Git:
111 |
112 | ```bash
113 | git push heroku main
114 | ```
115 |
116 | ---
117 |
118 | ### 10.5 Security Best Practices for Deployment
119 |
120 | 1. **Keep Your Token Secret:**
121 |
122 | * Use a `.env` file:
123 |
124 | ```env
125 | TOKEN="your_bot_token"
126 | ```
127 | * Load in code:
128 |
129 | ```python
130 | from dotenv import load_dotenv
131 | load_dotenv()
132 | bot.run(os.getenv('TOKEN'))
133 | ```
134 | 2. **Firewall Configuration:**
135 |
136 | ```bash
137 | sudo ufw allow 22 # SSH
138 | sudo ufw allow 80 # HTTP
139 | sudo ufw enable
140 | ```
141 | 3. **Reverse Proxy with Nginx:**
142 |
143 | ```nginx
144 | server {
145 | listen 80;
146 | server_name example.com;
147 |
148 | location / {
149 | proxy_pass http://localhost:8000;
150 | proxy_set_header Host $host;
151 | }
152 | }
153 | ```
154 |
155 | ---
156 |
157 | ### 10.6 Maintenance and Monitoring
158 |
159 | 1. **Monitoring with PM2:**
160 |
161 | ```bash
162 | pm2 logs my-bot --lines 100 # View last 100 log lines
163 | pm2 monit # Real-time monitoring
164 | ```
165 | 2. **Automated Updates:**
166 | Use a cron job to pull changes and restart nightly:
167 |
168 | ```bash
169 | 0 3 * * * cd /path/to/bot && git pull && pm2 restart my-bot
170 | ```
171 | 3. **Backups:**
172 |
173 | ```bash
174 | # Backup SQLite database
175 | cp database.db backup/database_$(date +%F).db
176 |
177 | # Upload backups to AWS S3
178 | aws s3 cp backup s3://my-bot-backups --recursive
179 | ```
180 |
181 | ---
182 |
183 | ### Hands-On Exercises for Chapter 10
184 |
185 | 1. Deploy your bot on Replit or Railway and verify it stays online 24/7.
186 | 2. Run your bot on a Linux server using PM2.
187 | 3. Create an automated backup system using cron jobs.
188 |
189 | ---
190 |
191 | ### Common Issues
192 |
193 | * **Bot Stops After a While:**
194 |
195 | * Ensure you’re using PM2 or a similar process manager.
196 | * Verify the server has sufficient CPU/RAM.
197 | * **`ImportError` on Startup:**
198 |
199 | * Check that all dependencies are listed in `requirements.txt`.
200 | * Run `pip install -r requirements.txt`.
201 |
202 | ---
203 |
204 | ### Pro Tips
205 |
206 | * For complex bots, consider using Docker to isolate the environment.
207 | * Always back up your database before deploying updates.
208 | * Implement CI/CD with GitHub Actions for automated testing and deployment.
209 |
210 | ---
211 |
212 | **Course Complete!** 🎉
213 | You now have the skills to build, extend, and deploy professional Discord bots. Keep learning, explore open-source bot projects on GitHub, and contribute to collaborative communities!
--------------------------------------------------------------------------------
/python/en/saeson11.md:
--------------------------------------------------------------------------------
1 | ## Chapter 11: Practical Projects to Solidify Your Skills
2 |
3 | ---
4 |
5 | ### Project 1: Poll Bot
6 |
7 | **Goal:** Build a bot that, with the `/poll` command, creates a customizable poll and processes the results.
8 |
9 | #### Implementation Steps:
10 |
11 | 1. **Register the Slash Command**
12 |
13 | ```python
14 | @bot.tree.command(name="poll", description="Create a poll")
15 | @app_commands.describe(question="The poll question", options="Comma-separated choices")
16 | async def poll(interaction: discord.Interaction, question: str, options: str):
17 | choices = [opt.strip() for opt in options.split(",")]
18 | ```
19 | 2. **Build the Embed & Add Reactions**
20 |
21 | ```python
22 | embed = discord.Embed(title=question, color=0x5865F2)
23 | for idx, choice in enumerate(choices, start=1):
24 | embed.add_field(name=f"Option {idx}", value=choice, inline=False)
25 |
26 | poll_msg = await interaction.channel.send(embed=embed)
27 | for emoji in ["1️⃣", "2️⃣", "3️⃣", "4️⃣"][:len(choices)]:
28 | await poll_msg.add_reaction(emoji)
29 | ```
30 |
31 | ---
32 |
33 | ### Project 2: Music Bot
34 |
35 | **Goal:** Create a bot that joins a voice channel and plays music from YouTube.
36 |
37 | #### Implementation Steps:
38 |
39 | 1. **Install Required Libraries**
40 |
41 | ```bash
42 | pip install yt-dlp discord.py[voice]
43 | ```
44 | 2. **Connect to Voice Channel & Play Audio**
45 |
46 | ```python
47 | @bot.command()
48 | async def play(ctx, url: str):
49 | if not ctx.author.voice:
50 | return await ctx.send("Please join a voice channel first!")
51 | channel = ctx.author.voice.channel
52 | voice_client = await channel.connect()
53 |
54 | ydl_opts = {"format": "bestaudio"}
55 | with yt_dlp.YoutubeDL(ydl_opts) as ydl:
56 | info = ydl.extract_info(url, download=False)
57 | audio_url = info["url"]
58 |
59 | voice_client.play(discord.FFmpegPCMAudio(audio_url))
60 | await ctx.send(f"🎶 Now playing: **{info['title']}**")
61 | ```
62 |
63 | ---
64 |
65 | ### Project 3: XP Leveling System
66 |
67 | **Goal:** Track user activity and award levels based on XP.
68 |
69 | #### Implementation Steps:
70 |
71 | 1. **Update XP in SQLite**
72 |
73 | ```python
74 | async def update_xp(user_id: int):
75 | async with aiosqlite.connect("xp.db") as db:
76 | await db.execute("""
77 | INSERT INTO users (user_id, xp)
78 | VALUES (?, 10)
79 | ON CONFLICT(user_id) DO UPDATE
80 | SET xp = xp + 10
81 | """, (user_id,))
82 | await db.commit()
83 | ```
84 | 2. **Check for Level Up**
85 |
86 | ```python
87 | @bot.event
88 | async def on_message(message):
89 | if message.author.bot:
90 | return
91 | await update_xp(message.author.id)
92 | user_xp = await get_xp(message.author.id)
93 | if user_xp >= 100:
94 | await message.channel.send(f"🎉 {message.author.mention} reached a new level!")
95 | await bot.process_commands(message)
96 | ```
97 |
98 | ---
99 |
100 | ### Project 4: Ticket System
101 |
102 | **Goal:** Let users create private support tickets with `/ticket`.
103 |
104 | #### Implementation Steps:
105 |
106 | 1. **Create the Ticket Channel**
107 |
108 | ```python
109 | @bot.tree.command(name="ticket", description="Open a support ticket")
110 | async def ticket(interaction: discord.Interaction):
111 | overwrites = {
112 | interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),
113 | interaction.user: discord.PermissionOverwrite(read_messages=True)
114 | }
115 | ticket_chan = await interaction.guild.create_text_channel(
116 | name=f"ticket-{interaction.user.name}",
117 | overwrites=overwrites
118 | )
119 | await ticket_chan.send(f"📩 {interaction.user.mention}, your ticket has been created!")
120 | ```
121 |
122 | ---
123 |
124 | ### Project 5: Mini-Games Bot
125 |
126 | **Goal:** Implement simple interactive games.
127 |
128 | #### Suggested Commands:
129 |
130 | 1. **Coin Flip**
131 |
132 | ```python
133 | @bot.command()
134 | async def coin(ctx):
135 | result = random.choice(["Heads", "Tails"])
136 | await ctx.send(f"🪙 Result: **{result}**")
137 | ```
138 | 2. **Random Number**
139 |
140 | ```python
141 | @bot.command()
142 | async def number(ctx, minimum: int, maximum: int):
143 | num = random.randint(minimum, maximum)
144 | await ctx.send(f"🎲 Your random number is **{num}**")
145 | ```
146 |
147 | ---
148 |
149 | ### Additional Challenges
150 |
151 | 1. **Weather Bot**
152 |
153 | * `/weather [city]` fetches and displays weather data from an API.
154 | 2. **Dictionary Bot**
155 |
156 | * `/define [word]` retrieves definitions from an online dictionary API.
157 | 3. **Virtual Economy Bot**
158 |
159 | * Use `!work` and `!buy` commands to earn and spend virtual currency on items.
160 |
161 | ---
162 |
163 | ### Common Issues & Solutions
164 |
165 | * **Poll Bot Doesn’t Handle Reactions:**
166 |
167 | * Implement `on_raw_reaction_add` to catch reactions across messages.
168 | * Enable the `Intents.reactions` if required.
169 | * **Music Bot Audio Errors:**
170 |
171 | * Ensure FFmpeg is installed (`sudo apt install ffmpeg`).
172 | * Validate usage of `discord.FFmpegPCMAudio`.
173 |
174 | ---
175 |
176 | ### Final Tips
177 |
178 | * Organize projects modularly—each command in its own file.
179 | * Use GitHub for version control and team collaboration.
180 | * For more ideas, see [Awesome Discord Bots Best Practices](https://github.com/meew0/discord-bot-best-practices).
181 |
182 | ---
183 |
184 | **Good luck!** 🚀
185 | Completing these projects makes you a professional Discord bot developer. Join the community, share your ideas, and bring them to life!
--------------------------------------------------------------------------------
/python/en/saeson2.md:
--------------------------------------------------------------------------------
1 | ## Chapter 2: Getting to Know Python Fundamentals
2 |
3 | ---
4 |
5 | ### 2.1 Variables and Data Types
6 |
7 | Variables are like boxes that store data. In Python, you don’t need to declare a type in advance (dynamic typing).
8 |
9 | #### Common Data Types
10 |
11 | * **String**
12 |
13 | ```python
14 | name = "Alice" # Text is enclosed in "" or ''
15 | message = 'Hello!'
16 | ```
17 | * **Integer and Float**
18 |
19 | ```python
20 | age = 20 # Integer
21 | price = 12.5 # Floating-point number
22 | ```
23 | * **Boolean**
24 |
25 | ```python
26 | is_online = True
27 | has_permission = False
28 | ```
29 | * **List**
30 |
31 | ```python
32 | users = ["Alice", "Bob", "Charlie"]
33 | print(users[0]) # Output: Alice
34 | ```
35 | * **Dictionary**
36 |
37 | ```python
38 | user = {
39 | "name": "Alice",
40 | "age": 25,
41 | "is_admin": True
42 | }
43 | print(user["name"]) # Output: Alice
44 | ```
45 |
46 | ---
47 |
48 | ### 2.2 Operators
49 |
50 | #### Arithmetic Operators
51 |
52 | ```python
53 | a = 10 + 5 # 15
54 | b = 20 - 3 # 17
55 | c = 6 * 2 # 12
56 | d = 10 / 2 # 5.0 (floating-point division)
57 | e = 10 // 3 # 3 (integer division)
58 | f = 10 % 3 # 1 (modulo)
59 | ```
60 |
61 | #### Comparison Operators
62 |
63 | ```python
64 | print(5 > 3) # True
65 | print(5 == 5) # True
66 | print(5 != 3) # True
67 | ```
68 |
69 | #### Logical Operators
70 |
71 | ```python
72 | has_account = True
73 | is_logged_in = False
74 | print(has_account and is_logged_in) # False
75 | print(has_account or is_logged_in) # True
76 | print(not has_account) # False
77 | ```
78 |
79 | ---
80 |
81 | ### 2.3 Control Flow
82 |
83 | #### `if` / `elif` / `else`
84 |
85 | ```python
86 | hour = 14
87 | if hour < 12:
88 | print("Good morning!")
89 | elif hour < 18:
90 | print("Good afternoon!")
91 | else:
92 | print("Good evening!")
93 | ```
94 |
95 | #### `for` Loop
96 |
97 | ```python
98 | for i in range(5): # 0 through 4
99 | print(i)
100 |
101 | for user in ["Alice", "Bob", "Charlie"]:
102 | print(f"Hello, {user}!")
103 | ```
104 |
105 | #### `while` Loop
106 |
107 | ```python
108 | count = 3
109 | while count > 0:
110 | print(count)
111 | count -= 1 # Decrement count each iteration
112 | ```
113 |
114 | ---
115 |
116 | ### 2.4 Functions
117 |
118 | Functions are reusable blocks of code that perform a specific task.
119 |
120 | #### Defining a Simple Function
121 |
122 | ```python
123 | def greet(name):
124 | return f"Hello, {name}!"
125 |
126 | print(greet("Alice")) # Output: Hello, Alice!
127 | ```
128 |
129 | #### Default Parameters
130 |
131 | ```python
132 | def multiply(a, b=2):
133 | return a * b
134 |
135 | print(multiply(5)) # 10 (uses b=2)
136 | print(multiply(5, 3)) # 15
137 | ```
138 |
139 | ---
140 |
141 | ### 2.5 Modules
142 |
143 | Modules are Python files that organize related functions and variables.
144 |
145 | #### Creating a Custom Module
146 |
147 | * **math\_utils.py**
148 |
149 | ```python
150 | PI = 3.14
151 |
152 | def square(x):
153 | return x ** 2
154 | ```
155 | * **main.py**
156 |
157 | ```python
158 | import math_utils
159 |
160 | print(math_utils.PI) # 3.14
161 | print(math_utils.square(4)) # 16
162 | ```
163 |
164 | ---
165 |
166 | ### Hands-On Exercises for Chapter 2
167 |
168 | 1. Write a function that takes two numbers and returns the larger one.
169 | 2. Create a list of user names and use a `for` loop to greet each one.
170 | 3. Build a dictionary to store user info (name, age, email).
171 |
172 | **Example for Exercise 1**:
173 |
174 | ```python
175 | def find_max(a, b):
176 | return a if a > b else b
177 |
178 | print(find_max(10, 5)) # 10
179 | ```
180 |
181 | ---
182 |
183 | ### Key Tips
184 |
185 | * Use descriptive English variable names (e.g., `user_age` instead of `a`).
186 | * Factor repeated code into functions to avoid duplication.
187 | * Use `print()` or VS Code’s debugger for troubleshooting.
188 |
189 | ---
190 |
191 | **Next Chapter:** Getting started with `discord.py` and building your first bot! 🚀
--------------------------------------------------------------------------------
/python/en/saeson3.md:
--------------------------------------------------------------------------------
1 | ## Chapter 3: Getting to Know the `discord.py` Library
2 |
3 | ---
4 |
5 | ### 3.1 Introduction to `discord.py`
6 |
7 | `discord.py` is a powerful, flexible Python library for building Discord bots. It provides simple tools to interact with the Discord API.
8 |
9 | #### Why `discord.py`?
10 |
11 | * **Beginner-Friendly:** Clean, readable syntax.
12 | * **Fully Asynchronous:** Efficient handling of concurrent tasks.
13 | * **Excellent Documentation:** The [official docs](https://discordpy.readthedocs.io/) include practical examples.
14 |
15 | ---
16 |
17 | ### 3.2 Installation and Setup
18 |
19 | #### Installing the Library
20 |
21 | In your terminal or CMD, run:
22 |
23 | ```bash
24 | pip install discord.py
25 | ```
26 |
27 | #### Alternative Forks
28 |
29 | * **nextcord:** A more up-to-date fork of `discord.py` with regular maintenance.
30 |
31 | ```bash
32 | pip install nextcord
33 | ```
34 |
35 | ---
36 |
37 | ### 3.3 Core Bot Structure
38 |
39 | #### 1. Importing Modules
40 |
41 | ```python
42 | import discord
43 | from discord.ext import commands
44 | ```
45 |
46 | #### 2. Configuring Intents
47 |
48 | Intents determine which Discord events your bot can receive.
49 |
50 | ```python
51 | intents = discord.Intents.default()
52 | intents.message_content = True # Grants access to message content
53 | ```
54 |
55 | #### 3. Creating the Bot Instance
56 |
57 | ```python
58 | bot = commands.Bot(
59 | command_prefix='!', # Command prefix (e.g., !ping)
60 | intents=intents
61 | )
62 | ```
63 |
64 | ---
65 |
66 | ### 3.4 Events
67 |
68 | Events let your bot react to things like going online or receiving messages.
69 |
70 | #### The `on_ready` Event
71 |
72 | Fires when the bot has successfully connected to Discord.
73 |
74 | ```python
75 | @bot.event
76 | async def on_ready():
77 | print(f'✅ {bot.user.name} is now online!')
78 | ```
79 |
80 | #### The `on_message` Event
81 |
82 | Triggers each time a message is sent in any channel the bot can see.
83 |
84 | ```python
85 | @bot.event
86 | async def on_message(message):
87 | if message.author == bot.user: # Ignore the bot’s own messages
88 | return
89 |
90 | if message.content == 'hello':
91 | await message.channel.send('Hello! How are you? 😊')
92 |
93 | await bot.process_commands(message) # Allows command processing
94 | ```
95 |
96 | ---
97 |
98 | ### 3.5 Simple Commands
99 |
100 | Use the `@commands.command()` decorator to define custom commands.
101 |
102 | #### The `ping` Command
103 |
104 | ```python
105 | @bot.command()
106 | async def ping(ctx):
107 | latency = round(bot.latency * 1000) # Latency in ms
108 | await ctx.reply(f'🏓 Pong! Latency: {latency}ms')
109 | ```
110 |
111 | #### Commands with Parameters
112 |
113 | ```python
114 | @bot.command()
115 | async def say(ctx, *, text):
116 | await ctx.send(text) # Usage: !say Hello World
117 | ```
118 |
119 | ---
120 |
121 | ### 3.6 Working with Embeds
122 |
123 | Embeds are richly formatted message blocks perfect for displaying information.
124 |
125 | #### Sending an Embed
126 |
127 | ```python
128 | @bot.command()
129 | async def info(ctx):
130 | embed = discord.Embed(
131 | title="Embed Title",
132 | description="General description",
133 | color=discord.Color.blue()
134 | )
135 | embed.add_field(name="Field 1", value="Value 1", inline=False)
136 | embed.set_thumbnail(url=ctx.author.avatar.url)
137 |
138 | await ctx.send(embed=embed)
139 | ```
140 |
141 | ---
142 |
143 | ### Complete Example Bot
144 |
145 | ```python
146 | import discord
147 | from discord.ext import commands
148 |
149 | intents = discord.Intents.default()
150 | intents.message_content = True
151 |
152 | bot = commands.Bot(command_prefix='!', intents=intents)
153 |
154 | @bot.event
155 | async def on_ready():
156 | print(f'✅ {bot.user} is now online!')
157 |
158 | @bot.command()
159 | async def ping(ctx):
160 | await ctx.reply(f'🏓 Pong! Latency: {round(bot.latency * 1000)}ms')
161 |
162 | bot.run('YOUR_TOKEN_HERE')
163 | ```
164 |
165 | ---
166 |
167 | ### Hands-On Exercises for Chapter 3
168 |
169 | 1. Create a command `!time` that sends back the current time.
170 | 2. Design an embed that displays the user’s name, ID, and join date.
171 | 3. Build a command `!add 5 10` that calculates the sum of two numbers.
172 |
173 | ---
174 |
175 | ### Common Issues
176 |
177 | * **Bot Doesn’t Respond to Messages:**
178 |
179 | * Ensure `intents.message_content = True`.
180 | * Use the correct command prefix (`!`).
181 | * **`Missing Intents` Error:**
182 |
183 | * In the [Discord Developer Portal](https://discord.com/developers/applications), enable the required intents.
184 |
185 | ---
186 |
187 | ### Key Tips
188 |
189 | * **Never** expose your bot token in public code (we’ll cover `.env` in later chapters).
190 | * For more complex bots, organize commands using Cogs (see Chapter 6).
191 | * Keep your library up to date before running:
192 |
193 | ```bash
194 | pip install --upgrade discord.py
195 | ```
196 |
197 | ---
198 |
199 | **Next Chapter:** Building your first advanced bot commands! 🚀
--------------------------------------------------------------------------------
/python/en/saeson4.md:
--------------------------------------------------------------------------------
1 | ## Chapter 4: Building Your First Bot
2 |
3 | ---
4 |
5 | ### 4.1 Initial Bot Setup
6 |
7 | #### 1. Create `main.py`
8 |
9 | ```python
10 | import discord
11 | from discord.ext import commands
12 | import datetime
13 |
14 | intents = discord.Intents.default()
15 | intents.message_content = True
16 |
17 | bot = commands.Bot(
18 | command_prefix="!",
19 | intents=intents,
20 | help_command=None # Disable the default help command
21 | )
22 | ```
23 |
24 | #### 2. Add the `on_ready` Event
25 |
26 | ```python
27 | @bot.event
28 | async def on_ready():
29 | print(f"✅ {bot.user.name} is now online!")
30 | print(f"Connected to {len(bot.guilds)} servers")
31 | print(f"Startup time: {datetime.datetime.now()}")
32 | ```
33 |
34 | ---
35 |
36 | ### 4.2 Basic Commands
37 |
38 | #### 1. The `!hello` Command
39 |
40 | ```python
41 | @bot.command()
42 | async def سلام(ctx):
43 | await ctx.reply(f"Hello, {ctx.author.mention}! 😊")
44 | ```
45 |
46 | #### 2. The `!time` Command
47 |
48 | ```python
49 | @bot.command()
50 | async def time(ctx):
51 | now = datetime.datetime.now().strftime("%H:%M:%S")
52 | await ctx.send(f"🕒 Current time: **{now}**")
53 | ```
54 |
55 | #### 3. The `!add` Command with Arguments
56 |
57 | ```python
58 | @bot.command()
59 | async def add(ctx, num1: int, num2: int):
60 | result = num1 + num2
61 | await ctx.send(f"Result: `{num1} + {num2} = {result}`")
62 | ```
63 |
64 | ---
65 |
66 | ### 4.3 Advanced Embeds
67 |
68 | #### The `!user` Command
69 |
70 | ```python
71 | @bot.command()
72 | async def user(ctx, member: discord.Member = None):
73 | member = member or ctx.author # Default to the author if no member is mentioned
74 |
75 | embed = discord.Embed(
76 | title=f"ℹ️ Information for {member.name}",
77 | color=discord.Color.green()
78 | )
79 | embed.set_thumbnail(url=member.avatar.url)
80 | embed.add_field(name="Tag", value=member.mention)
81 | embed.add_field(name="ID", value=member.id)
82 | embed.add_field(name="Joined At", value=member.joined_at.strftime("%Y/%m/%d"))
83 |
84 | await ctx.send(embed=embed)
85 | ```
86 |
87 | ---
88 |
89 | ### 4.4 Error Handling
90 |
91 | #### Missing Permissions
92 |
93 | ```python
94 | @bot.event
95 | async def on_command_error(ctx, error):
96 | if isinstance(error, commands.MissingPermissions):
97 | await ctx.send("⛔ You do not have the required permissions!")
98 | ```
99 |
100 | #### Missing Required Argument
101 |
102 | ```python
103 | @add.error
104 | async def add_error(ctx, error):
105 | if isinstance(error, commands.MissingRequiredArgument):
106 | await ctx.send("⚠️ Please provide two numbers!\nExample: `!add 5 10`")
107 | ```
108 |
109 | ---
110 |
111 | ### 4.5 Custom Help Command
112 |
113 | ```python
114 | @bot.command()
115 | async def help(ctx):
116 | embed = discord.Embed(
117 | title="📚 Command List",
118 | description="Command prefix: `!`",
119 | color=discord.Color.blue()
120 | )
121 | embed.add_field(
122 | name="General",
123 | value="`hello` `time` `user [@mention]`",
124 | inline=False
125 | )
126 | embed.add_field(
127 | name="Math",
128 | value="`add `",
129 | inline=False
130 | )
131 |
132 | await ctx.send(embed=embed)
133 | ```
134 |
135 | ---
136 |
137 | ### 4.6 Running the Bot
138 |
139 | ```python
140 | # In Chapter 7 we'll cover using a .env file
141 | TOKEN = "YOUR_TOKEN_HERE"
142 |
143 | if __name__ == "__main__":
144 | bot.run(TOKEN)
145 | ```
146 |
147 | ---
148 |
149 | ### Hands-On Exercises for Chapter 4
150 |
151 | 1. Create a `!coin` command that flips a coin and returns heads or tails.
152 | 2. Implement a `!purge` command that deletes a specified number of messages (requires Manage Messages permission).
153 | 3. Set up a welcome message event so the bot greets new members when they join:
154 |
155 | ```python
156 | @bot.event
157 | async def on_member_join(member):
158 | channel = member.guild.system_channel
159 | await channel.send(f"🎉 Welcome to the server, {member.mention}!")
160 | ```
161 |
162 | ---
163 |
164 | ### Common Issues & Solutions
165 |
166 | * **Commands Aren’t Running**
167 |
168 | * Ensure `intents.message_content = True` is set.
169 | * Restart the bot after changes (`Ctrl+C` and `python main.py`).
170 | * **Bot Can’t Mention Members**
171 |
172 | * In the Developer Portal, enable the **Server Members Intent** for your bot.
173 |
174 | ---
175 |
176 | ### Key Tips
177 |
178 | * Use `ctx.reply()` instead of `ctx.send()` when you want to mention the user.
179 | * Accept `discord.Member` parameters to automatically convert mentions into Member objects.
180 | * Handle errors with `@bot.event` and `on_command_error` for better user feedback.
181 |
182 | ---
183 |
184 | **Next Chapter:** Working with Embeds, file attachments, and more! 🚀
--------------------------------------------------------------------------------
/python/en/saeson5.md:
--------------------------------------------------------------------------------
1 | ## Chapter 5: Working with Embeds and Files
2 |
3 | ---
4 |
5 | ### 5.1 Creating Professional Embeds
6 |
7 | Embeds are richly formatted messages that display information in an organized, visually appealing way.
8 |
9 | #### Building a Simple Embed
10 |
11 | ```python
12 | from discord import Embed
13 |
14 | @bot.command()
15 | async def announcement(ctx):
16 | embed = Embed(
17 | title="📢 Important Announcement",
18 | description="Welcome to our server!",
19 | color=0x00FF00 # HEX color code (green)
20 | )
21 | embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar.url)
22 | await ctx.send(embed=embed)
23 | ```
24 |
25 | #### Adding Fields and an Image
26 |
27 | ```python
28 | @bot.command()
29 | async def profile(ctx, member: discord.Member = None):
30 | member = member or ctx.author
31 |
32 | embed = Embed(
33 | title=f"📁 {member.name}'s Profile",
34 | color=discord.Color.blurple()
35 | )
36 | embed.set_thumbnail(url=member.avatar.url)
37 | embed.add_field(
38 | name="Joined On",
39 | value=member.joined_at.strftime("%Y/%m/%d"),
40 | inline=False
41 | )
42 | embed.add_field(
43 | name="Role Count",
44 | value=len(member.roles),
45 | inline=True
46 | )
47 | embed.set_image(url="https://example.com/banner.png") # Banner at bottom
48 |
49 | await ctx.send(embed=embed)
50 | ```
51 |
52 | ---
53 |
54 | ### 5.2 Sending and Receiving Files
55 |
56 | #### 1. Sending a Local File
57 |
58 | ```python
59 | @bot.command()
60 | async def send_image(ctx):
61 | file = discord.File("path/to/image.jpg", filename="image.jpg")
62 | await ctx.send(file=file)
63 | ```
64 |
65 | #### 2. Downloading and Sending a Remote File
66 |
67 | ```python
68 | import aiohttp
69 | from io import BytesIO
70 |
71 | @bot.command()
72 | async def download(ctx, url: str):
73 | async with aiohttp.ClientSession() as session:
74 | async with session.get(url) as resp:
75 | if resp.status == 200:
76 | data = await resp.read()
77 | file = discord.File(BytesIO(data), filename="download.png")
78 | await ctx.send(file=file)
79 | ```
80 |
81 | #### 3. Saving User-Uploaded Attachments
82 |
83 | ```python
84 | @bot.event
85 | async def on_message(message):
86 | if message.attachments:
87 | attachment = message.attachments[0]
88 | await attachment.save(f"downloads/{attachment.filename}")
89 | await message.channel.send("✅ File saved!")
90 | await bot.process_commands(message)
91 | ```
92 |
93 | ---
94 |
95 | ### 5.3 Combining Embeds with Attachments
96 |
97 | You can send an embed and a file together:
98 |
99 | ```python
100 | @bot.command()
101 | async def card(ctx):
102 | embed = Embed(title="🎴 Special Card", color=0xFFD700)
103 | embed.set_image(url="attachment://card.png") # Reference the attached file
104 |
105 | file = discord.File("images/card.png", filename="card.png")
106 | await ctx.send(embed=embed, file=file)
107 | ```
108 |
109 | ---
110 |
111 | ### 5.4 Dynamic Embeds with Live Data
112 |
113 | #### Example: Displaying Server Info
114 |
115 | ```python
116 | @bot.command()
117 | async def server(ctx):
118 | guild = ctx.guild
119 | embed = Embed(title=guild.name, description=guild.description or "No description")
120 | embed.add_field(name="Member Count", value=guild.member_count)
121 | embed.add_field(name="Owner", value=guild.owner.mention)
122 | if guild.icon:
123 | embed.set_thumbnail(url=guild.icon.url)
124 |
125 | await ctx.send(embed=embed)
126 | ```
127 |
128 | ---
129 |
130 | ### Hands-On Exercises for Chapter 5
131 |
132 | 1. **Meme Generator**: Create a `!meme [text]` command that downloads a base image and overlays the user’s text on it using the Pillow library.
133 | 2. **Attachment Preview**: Automatically display any user-uploaded image inside an embed when they send it.
134 | 3. **Stats Command**: Build a `!stats` command that shows the user’s message count in an embed.
135 |
136 | ---
137 |
138 | ### Common Issues
139 |
140 | * **File Doesn’t Send**:
141 |
142 | * Verify the file path is correct.
143 | * Ensure you specify the file extension (e.g., `.jpg`) in `filename`.
144 | * **Embed Image Not Showing**:
145 |
146 | * Use `attachment://filename.extension` in `set_image`.
147 | * Make sure the file is attached to the same message as the embed.
148 |
149 | ---
150 |
151 | ### Key Tips
152 |
153 | * You can specify embed colors using HEX codes or Discord’s built-in color helpers (e.g., `discord.Color.red()`).
154 | * Discord limits attachment size to **8 MB** on free accounts.
155 | * For image processing, install Pillow:
156 |
157 | ```bash
158 | pip install pillow
159 | ```
160 |
161 | ---
162 |
163 | **Next Chapter:** Organizing your code with Cogs and creating more advanced commands! 🛠️
--------------------------------------------------------------------------------
/python/en/saeson6.md:
--------------------------------------------------------------------------------
1 | ## Chapter 6: Advanced Commands (Cogs and Command Decorators)
2 |
3 | ---
4 |
5 | ### 6.1 Introducing Cogs (Modular Code Organization)
6 |
7 | Cogs are classes that group commands, events, and configuration into modules, making your code cleaner and easier to maintain.
8 |
9 | #### Benefits of Using Cogs
10 |
11 | * Cleaner, more maintainable code
12 | * Ability to load/unload commands without restarting the bot
13 | * Separate error handling per module
14 |
15 | ---
16 |
17 | ### 6.2 Creating Your First Cog
18 |
19 | #### 1. Create `cogs/moderate.py`
20 |
21 | ```python
22 | from discord.ext import commands
23 |
24 | class Moderate(commands.Cog):
25 | def __init__(self, bot):
26 | self.bot = bot
27 |
28 | # Purge messages command
29 | @commands.command()
30 | @commands.has_permissions(manage_messages=True)
31 | async def purge(self, ctx, limit: int = 10):
32 | await ctx.channel.purge(limit=limit + 1) # +1 to delete the command message
33 | msg = await ctx.send(f"✅ Deleted {limit} messages!", delete_after=5)
34 |
35 | # Error handler for missing permissions
36 | @purge.error
37 | async def purge_error(self, ctx, error):
38 | if isinstance(error, commands.MissingPermissions):
39 | await ctx.send("⛔ You don’t have permission to manage messages!")
40 |
41 | async def setup(bot):
42 | await bot.add_cog(Moderate(bot))
43 | ```
44 |
45 | #### 2. Load the Cog in `main.py`
46 |
47 | ```python
48 | async def main():
49 | await bot.load_extension("cogs.moderate")
50 |
51 | if __name__ == "__main__":
52 | import asyncio
53 | asyncio.run(main())
54 | bot.run(TOKEN)
55 | ```
56 |
57 | ---
58 |
59 | ### 6.3 Advanced Command Decorators
60 |
61 | #### 1. User and Permission Checks
62 |
63 | ```python
64 | @commands.has_role("Admin") # Requires a specific role
65 | @commands.has_permissions(kick_members=True) # Requires specific permission
66 | @commands.is_owner() # Only the bot owner can use
67 | ```
68 |
69 | #### 2. Command Cooldowns
70 |
71 | ```python
72 | @commands.cooldown(rate=1, per=30, type=commands.BucketType.user) # 30-second cooldown per user
73 | async def claim_reward(ctx):
74 | await ctx.send("🎉 You received 100 coins!")
75 | ```
76 |
77 | #### 3. Hybrid Commands (Slash + Prefix)
78 |
79 | ```python
80 | from discord import app_commands
81 |
82 | @commands.hybrid_command(name="ban", description="Ban a user")
83 | @app_commands.describe(user="The member to ban")
84 | async def ban(ctx, user: discord.Member):
85 | await user.ban()
86 | await ctx.send(f"✅ {user.mention} has been banned!")
87 | ```
88 |
89 | ---
90 |
91 | ### 6.4 Global Error Handling in Cogs
92 |
93 | ```python
94 | class Moderate(commands.Cog):
95 | # ...
96 |
97 | @commands.Cog.listener()
98 | async def on_command_error(self, ctx, error):
99 | if isinstance(error, commands.CommandNotFound):
100 | await ctx.send("❌ Command not found!")
101 | ```
102 |
103 | ---
104 |
105 | ### 6.5 Building a Custom Help Command
106 |
107 | ```python
108 | class Help(commands.Cog):
109 | def __init__(self, bot):
110 | self.bot = bot
111 |
112 | @commands.hybrid_command(name="help")
113 | async def help(self, ctx):
114 | embed = discord.Embed(title="📚 Help Menu")
115 | for cog_name, cog in self.bot.cogs.items():
116 | command_list = [f"`{cmd.name}`" for cmd in cog.get_commands()]
117 | embed.add_field(name=cog_name, value=" ".join(command_list) or "No commands", inline=False)
118 | await ctx.send(embed=embed)
119 |
120 | async def setup(bot):
121 | await bot.add_cog(Help(bot))
122 | ```
123 |
124 | ---
125 |
126 | ### 6.6 Hands-On Exercises
127 |
128 | 1. Create a new Cog named `Fun` and move commands like `coin` and `number` into it.
129 | 2. Convert the `!ban` command into a slash-only command.
130 | 3. Build a `!claim` command with a per-user cooldown of 3 uses per hour.
131 |
132 | ---
133 |
134 | ### Common Issues
135 |
136 | * **Cog fails to load**:
137 |
138 | * Verify the file path (`cogs/moderate.py`) is correct.
139 | * Confirm you’re calling `await bot.load_extension("cogs.moderate")`.
140 | * **Commands don’t appear**:
141 |
142 | * Ensure each command method is decorated with `@commands.command()` or `@commands.hybrid_command()`.
143 |
144 | ---
145 |
146 | ### Pro Tips
147 |
148 | * Keep each Cog in its own file for clarity.
149 | * Pick a consistent language (English or another) for command names.
150 | * Use `@commands.check()` for custom validation logic.
151 |
152 | ---
153 |
154 | **Next Chapter:** Slash Commands and Modern Interactions! ✨
--------------------------------------------------------------------------------
/python/en/saeson7.md:
--------------------------------------------------------------------------------
1 | ## Chapter 7: Slash Commands
2 |
3 | ---
4 |
5 | ### 7.1 Introduction to Slash Commands
6 |
7 | Slash commands (prefixed with `/`) provide a modern, user-friendly interface for interacting with Discord bots.
8 |
9 | * **Benefits:**
10 |
11 | * No need for a text prefix (`!`, `?`, etc.).
12 | * Built-in UI with command suggestions and auto-complete.
13 | * Structured parameters (text, numbers, users, channels, etc.).
14 |
15 | ---
16 |
17 | ### 7.2 Initial Setup
18 |
19 | #### Enabling Slash Commands
20 |
21 | 1. In the Discord Developer Portal, under your application’s **Bot** settings, enable the following privileged gateway intents:
22 |
23 | * **Server Members Intent**
24 | * **Message Content Intent**
25 | 2. In your code, import the app\_commands module:
26 |
27 | ```python
28 | from discord import app_commands
29 | ```
30 |
31 | ---
32 |
33 | ### 7.3 Creating Your First Slash Command
34 |
35 | #### The `/ping` Command
36 |
37 | ```python
38 | @bot.tree.command(name="ping", description="Check the bot’s latency")
39 | async def ping(interaction: discord.Interaction):
40 | latency = round(bot.latency * 1000)
41 | await interaction.response.send_message(f"🏓 Pong! Latency: {latency}ms")
42 | ```
43 |
44 | ---
45 |
46 | ### 7.4 Registering and Syncing Commands
47 |
48 | Slash commands must be synced with Discord before they appear.
49 |
50 | #### 1. Sync commands to a specific guild (fast updates):
51 |
52 | ```python
53 | @bot.command()
54 | @commands.is_owner()
55 | async def sync(interaction: discord.Interaction):
56 | await bot.tree.sync(guild=discord.Object(id=GUILD_ID)) # replace GUILD_ID
57 | await interaction.response.send_message("✅ Commands synced to this server!")
58 | ```
59 |
60 | #### 2. Sync globally (available in all guilds):
61 |
62 | ```python
63 | @bot.command()
64 | @commands.is_owner()
65 | async def sync_global(interaction: discord.Interaction):
66 | await bot.tree.sync()
67 | await interaction.response.send_message("✅ Global commands synced!")
68 | ```
69 |
70 | ---
71 |
72 | ### 7.5 Advanced Parameters
73 |
74 | #### 1. Taking User Input
75 |
76 | ```python
77 | @bot.tree.command(name="add", description="Add two numbers")
78 | @app_commands.describe(a="First number", b="Second number")
79 | async def add(interaction: discord.Interaction, a: int, b: int):
80 | await interaction.response.send_message(f"Result: {a + b}")
81 | ```
82 |
83 | #### 2. Auto-Complete Suggestions
84 |
85 | ```python
86 | @bot.tree.command(name="color", description="Choose a color")
87 | @app_commands.describe(color="Select a color")
88 | @app_commands.autocomplete(color=autocomplete_color)
89 | async def color(interaction: discord.Interaction, color: str):
90 | await interaction.response.send_message(f"Selected color: {color}")
91 |
92 | async def autocomplete_color(interaction: discord.Interaction, current: str) -> list[app_commands.Choice[str]]:
93 | options = ["Red", "Blue", "Green", "Yellow"]
94 | return [
95 | app_commands.Choice(name=opt, value=opt)
96 | for opt in options if current.lower() in opt.lower()
97 | ]
98 | ```
99 |
100 | ---
101 |
102 | ### 7.6 Hybrid Commands
103 |
104 | Commands that work both as slash commands and with a prefix:
105 |
106 | ```python
107 | from discord.ext import commands
108 |
109 | @commands.hybrid_command(name="ban", description="Ban a member")
110 | @app_commands.describe(member="The member to ban")
111 | @commands.has_permissions(ban_members=True)
112 | async def ban(ctx: commands.Context, member: discord.Member):
113 | await member.ban()
114 | await ctx.send(f"✅ {member.mention} has been banned!")
115 | ```
116 |
117 | ---
118 |
119 | ### 7.7 Error Handling
120 |
121 | #### Missing Permissions Error
122 |
123 | ```python
124 | @ban.error
125 | async def ban_error(ctx: commands.Context, error):
126 | if isinstance(error, commands.MissingPermissions):
127 | await ctx.send("⛔ You don’t have permission to ban members!")
128 | ```
129 |
130 | ---
131 |
132 | ### Hands-On Exercises for Chapter 7
133 |
134 | 1. Create a `/time` command that displays the current time.
135 | 2. Build a `/poll [question]` command that posts a reaction-based poll.
136 | 3. Implement an auto-complete command for `/weather [city]` with suggestions like “Tehran,” “Isfahan,” “Shiraz.”
137 |
138 | ---
139 |
140 | ### Common Issues
141 |
142 | * **Slash commands not appearing:**
143 |
144 | * Ensure you call `await bot.tree.sync()` after logging in.
145 | * Wait up to 24 hours for global commands to propagate.
146 | * **Bot doesn’t respond to commands:**
147 |
148 | * Make sure you have an `on_ready` event to sync commands.
149 | * Double-check your intents in the Developer Portal.
150 |
151 | ---
152 |
153 | ### Key Tips
154 |
155 | * During development, sync commands to a test server for instant updates.
156 | * Always use `interaction.response.send_message()` instead of `channel.send()`.
157 | * Define parameters with types (`discord.Member`, `int`, etc.) for built-in validation.
158 |
159 | ---
160 |
161 | **Next Chapter:** Database integration and persistent user data! 🗄️
--------------------------------------------------------------------------------
/python/en/saeson8.md:
--------------------------------------------------------------------------------
1 | ## Chapter 8: Working with Databases
2 |
3 | ---
4 |
5 | ### 8.1 Why Use a Database?
6 |
7 | Discord bots often need to store persistent data—such as user XP, server settings, logs, and more—in a database.
8 |
9 | * **Common Database Options:**
10 |
11 | * **SQLite:** Lightweight, serverless, ideal for small projects.
12 | * **PostgreSQL/MySQL:** Powerful SQL databases for larger applications.
13 | * **MongoDB:** Flexible, document-based NoSQL database.
14 |
15 | ---
16 |
17 | ### 8.2 Using SQLite (Simplest Option)
18 |
19 | #### 1. Install the Async Library
20 |
21 | ```bash
22 | pip install aiosqlite
23 | ```
24 |
25 | #### 2. Create and Initialize the Database
26 |
27 | ```python
28 | import aiosqlite
29 |
30 | async def create_db():
31 | async with aiosqlite.connect("database.db") as db:
32 | await db.execute("""
33 | CREATE TABLE IF NOT EXISTS users (
34 | user_id INTEGER PRIMARY KEY,
35 | xp INTEGER DEFAULT 0,
36 | level INTEGER DEFAULT 1
37 | )
38 | """)
39 | await db.commit()
40 | ```
41 |
42 | #### 3. Adding a User Record
43 |
44 | ```python
45 | async def add_user(user_id: int):
46 | async with aiosqlite.connect("database.db") as db:
47 | await db.execute(
48 | "INSERT OR IGNORE INTO users (user_id) VALUES (?)",
49 | (user_id,)
50 | )
51 | await db.commit()
52 | ```
53 |
54 | #### 4. Retrieving a User Record
55 |
56 | ```python
57 | async def get_user(user_id: int):
58 | async with aiosqlite.connect("database.db") as db:
59 | cursor = await db.execute(
60 | "SELECT * FROM users WHERE user_id = ?",
61 | (user_id,)
62 | )
63 | return await cursor.fetchone() # Returns (user_id, xp, level)
64 | ```
65 |
66 | ---
67 |
68 | ### 8.3 XP System with SQLite
69 |
70 | #### Awarding XP on Message
71 |
72 | ```python
73 | @bot.event
74 | async def on_message(message):
75 | if message.author.bot:
76 | return
77 |
78 | user_id = message.author.id
79 | await add_user(user_id) # Ensure the user exists
80 |
81 | async with aiosqlite.connect("database.db") as db:
82 | await db.execute(
83 | "UPDATE users SET xp = xp + ? WHERE user_id = ?",
84 | (10, user_id)
85 | )
86 | await db.commit()
87 |
88 | await bot.process_commands(message)
89 | ```
90 |
91 | #### The `!level` Command
92 |
93 | ```python
94 | @bot.command()
95 | async def level(ctx):
96 | user_data = await get_user(ctx.author.id)
97 | if not user_data:
98 | return await ctx.send("Error: User not found!")
99 |
100 | embed = discord.Embed(
101 | title=f"{ctx.author.name}'s Level",
102 | color=0x00FF00
103 | )
104 | embed.add_field(name="XP", value=user_data[1])
105 | embed.add_field(name="Level", value=user_data[2])
106 | await ctx.send(embed=embed)
107 | ```
108 |
109 | ---
110 |
111 | ### 8.4 Using PostgreSQL (Advanced)
112 |
113 | #### 1. Install `asyncpg`
114 |
115 | ```bash
116 | pip install asyncpg
117 | ```
118 |
119 | #### 2. Create a Connection Pool
120 |
121 | ```python
122 | import asyncpg
123 |
124 | async def create_pool():
125 | return await asyncpg.create_pool(
126 | user="postgres",
127 | password="password",
128 | database="mydb",
129 | host="localhost"
130 | )
131 | ```
132 |
133 | #### 3. Querying the Database
134 |
135 | ```python
136 | pool = await create_pool()
137 |
138 | async def get_user_pg(user_id: int):
139 | async with pool.acquire() as conn:
140 | return await conn.fetchrow(
141 | "SELECT * FROM users WHERE user_id = $1",
142 | user_id
143 | )
144 | ```
145 |
146 | ---
147 |
148 | ### 8.5 Storing Data in JSON (For Very Small Projects)
149 |
150 | #### 1. Save and Load Functions
151 |
152 | ```python
153 | import json
154 |
155 | def save_data(data):
156 | with open("data.json", "w", encoding="utf-8") as f:
157 | json.dump(data, f, ensure_ascii=False)
158 |
159 | def load_data():
160 | try:
161 | with open("data.json", "r", encoding="utf-8") as f:
162 | return json.load(f)
163 | except FileNotFoundError:
164 | return {}
165 | ```
166 |
167 | #### 2. Example Usage
168 |
169 | ```python
170 | data = load_data()
171 | data[str(user_id)] = {"xp": 100, "level": 2}
172 | save_data(data)
173 | ```
174 |
175 | ---
176 |
177 | ### 8.6 Database Security Best Practices
178 |
179 | * **Use Parameterized Queries** to prevent SQL injection:
180 |
181 | ```python
182 | # ❌ Vulnerable
183 | await db.execute(f"SELECT * FROM users WHERE user_id = {user_id}")
184 |
185 | # ✅ Safe
186 | await db.execute("SELECT * FROM users WHERE user_id = ?", (user_id,))
187 | ```
188 | * **Store Credentials in `.env`:**
189 |
190 | ```env
191 | DB_PASSWORD="your_password"
192 | ```
193 |
194 | ---
195 |
196 | ### Hands-On Exercises for Chapter 8
197 |
198 | 1. Build a system that awards 5 XP per message and levels users up every 100 XP.
199 | 2. Create a `!leaderboard` command showing the top 10 users by XP.
200 | 3. Store and retrieve server-specific settings (like command prefix) in your database.
201 |
202 | ---
203 |
204 | ### Common Issues
205 |
206 | * **Database Connection Errors:**
207 |
208 | * Ensure the DB server is running (for PostgreSQL/MySQL).
209 | * Double-check connection credentials.
210 | * **Data Not Persisting:**
211 |
212 | * Remember to call `commit()` after `INSERT` or `UPDATE` queries.
213 |
214 | ---
215 |
216 | ### Key Tips
217 |
218 | * For larger projects, consider using an ORM such as SQLAlchemy.
219 | * In high-traffic bots, leverage connection pooling for performance.
220 | * Always verify your database schema on startup (e.g., by running your `CREATE TABLE` scripts).
221 |
222 | ---
223 |
224 | **Next Chapter:** Server and User Management! ⚙️
--------------------------------------------------------------------------------
/python/en/saeson9.md:
--------------------------------------------------------------------------------
1 | ## Chapter 9: Server and User Management
2 |
3 | ---
4 |
5 | ### 9.1 Required Permissions
6 |
7 | To manage servers and members, your bot needs the appropriate permissions. You can configure these in code or in the Discord Developer Portal.
8 |
9 | #### Enabling Intents
10 |
11 | * **Server Members Intent**: Access to the member list.
12 | * **Moderation Intents**: For muting or banning users.
13 |
14 | #### Setting Permissions in Code
15 |
16 | ```python
17 | intents = discord.Intents.default()
18 | intents.members = True # Access to guild members
19 | intents.moderation = True # Access to moderation actions
20 |
21 | bot = commands.Bot(
22 | command_prefix="!",
23 | intents=intents
24 | )
25 | ```
26 |
27 | ---
28 |
29 | ### 9.2 Member Management Commands
30 |
31 | #### 1. Ban Command
32 |
33 | ```python
34 | @bot.command()
35 | @commands.has_permissions(ban_members=True)
36 | async def ban(ctx, member: discord.Member, reason: str = "No reason provided"):
37 | await member.ban(reason=reason)
38 | await ctx.send(f"✅ {member.mention} was banned!\nReason: **{reason}**")
39 |
40 | @ban.error
41 | async def ban_error(ctx, error):
42 | if isinstance(error, commands.MissingPermissions):
43 | await ctx.send("⛔ You don’t have permission to ban members!")
44 | ```
45 |
46 | #### 2. Unban Command
47 |
48 | ```python
49 | @bot.command()
50 | @commands.has_permissions(ban_members=True)
51 | async def unban(ctx, user_id: int):
52 | user = await bot.fetch_user(user_id)
53 | await ctx.guild.unban(user)
54 | await ctx.send(f"✅ {user.mention} was unbanned!")
55 | ```
56 |
57 | #### 3. Mute Command
58 |
59 | ```python
60 | @bot.command()
61 | @commands.has_permissions(moderate_members=True)
62 | async def mute(ctx, member: discord.Member, minutes: int = 10):
63 | duration = datetime.timedelta(minutes=minutes)
64 | await member.timeout(duration)
65 | await ctx.send(f"⏳ {member.mention} has been muted for **{minutes} minutes**!")
66 | ```
67 |
68 | ---
69 |
70 | ### 9.3 Message Management
71 |
72 | #### 1. Purge Command
73 |
74 | ```python
75 | @bot.command()
76 | @commands.has_permissions(manage_messages=True)
77 | async def purge(ctx, limit: int = 10):
78 | await ctx.channel.purge(limit=limit + 1) # +1 to include the command message
79 | msg = await ctx.send(f"✅ Deleted {limit} messages!", delete_after=5)
80 |
81 | @purge.error
82 | async def purge_error(ctx, error):
83 | if isinstance(error, commands.MissingPermissions):
84 | await ctx.send("⛔ You don’t have permission to manage messages!")
85 | ```
86 |
87 | #### 2. Report Message Command
88 |
89 | ```python
90 | @bot.command()
91 | async def report(ctx, message_id: int):
92 | message = await ctx.channel.fetch_message(message_id)
93 | embed = discord.Embed(
94 | title="⚠️ Message Report",
95 | description=message.content,
96 | color=discord.Color.red()
97 | )
98 | embed.set_author(name=message.author.name, icon_url=message.author.avatar.url)
99 | admin_channel = bot.get_channel(ADMIN_CHANNEL_ID) # replace with your admin channel ID
100 | await admin_channel.send(embed=embed)
101 | ```
102 |
103 | ---
104 |
105 | ### 9.4 Role Management
106 |
107 | #### 1. Add Role to a Member
108 |
109 | ```python
110 | @bot.command()
111 | @commands.has_permissions(manage_roles=True)
112 | async def add_role(ctx, member: discord.Member, role: discord.Role):
113 | await member.add_roles(role)
114 | await ctx.send(f"✅ Role {role.mention} added to {member.mention}!")
115 | ```
116 |
117 | #### 2. Create a New Role
118 |
119 | ```python
120 | @bot.command()
121 | @commands.has_permissions(manage_roles=True)
122 | async def create_role(ctx, name: str, color: str = "FFFFFF"):
123 | color_int = int(color, 16) # Convert HEX to int
124 | await ctx.guild.create_role(name=name, color=discord.Color(color_int))
125 | await ctx.send(f"✅ Role **{name}** has been created!")
126 | ```
127 |
128 | ---
129 |
130 | ### 9.5 Ticket System
131 |
132 | #### 1. Create a Ticket Channel
133 |
134 | ```python
135 | @bot.command()
136 | @commands.has_permissions(manage_channels=True)
137 | async def ticket(ctx, reason: str):
138 | overwrites = {
139 | ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False),
140 | ctx.author: discord.PermissionOverwrite(read_messages=True)
141 | }
142 | channel = await ctx.guild.create_text_channel(
143 | name=f"ticket-{ctx.author.name}",
144 | overwrites=overwrites
145 | )
146 | await channel.send(f"📩 Your ticket was created for reason: **{reason}**")
147 | ```
148 |
149 | #### 2. Close a Ticket
150 |
151 | ```python
152 | @bot.command()
153 | async def close(ctx):
154 | if "ticket-" in ctx.channel.name:
155 | await ctx.channel.delete()
156 | ```
157 |
158 | ---
159 |
160 | ### Hands-On Exercises for Chapter 9
161 |
162 | 1. **Activity Leaderboard:** Create a command that ranks members by message count.
163 | 2. **Mute Logging:** When muting a member, log the reason in a designated channel.
164 | 3. **Create Channel Command:** Build `!create_channel [name]` to create a new text channel.
165 |
166 | ---
167 |
168 | ### Common Issues
169 |
170 | * **Bot Can’t Ban/Mute Members:**
171 |
172 | * Ensure the bot’s role is higher than the target member’s role in the server hierarchy.
173 | * Verify the bot has the necessary permissions in the server settings.
174 | * **Missing Permissions Error:**
175 |
176 | * Use the `@commands.has_permissions()` decorator on your command.
177 |
178 | ---
179 |
180 | ### Security Best Practices
181 |
182 | * Avoid granting **Administrator** permissions to your bot unless absolutely necessary.
183 | * For sensitive commands, consider implementing a two-factor verification system for moderators.
184 | * Log all moderation actions to a secure, private channel for audit purposes.
185 |
186 | ---
187 |
188 | **Next Chapter:** Professional Deployment and Maintenance! 🚀
--------------------------------------------------------------------------------
/python/per/README.md:
--------------------------------------------------------------------------------
1 | # فهرست مطالب
2 |
3 | ### [**فصل ۱: مقدمه و آماده سازی محیط کار**](./saeson1.md)
4 | 1. **برنامه نویسی چیست؟**
5 | - چرا دیسکورد و پایتون؟
6 | - کاربرد ربات های دیسکورد.
7 | 2. **ابزار های مورد نیاز**
8 | - نصب پایتون و pip.
9 | - معرفی ویرایشگر کد (مثلاً VS Code یا PyCharm).
10 | - ساخت بات در پنل توسعه دهندگان دیسکورد (Developer Portal).
11 | - دریافت توکن (Token) بات.
12 |
13 | ---
14 |
15 | ### [**فصل ۲: آشنایی با مفاهیم پایه پایتون**](./saeson2.md)
16 | 1. **متغیر ها و انواع داده**
17 | - رشته ها، اعداد، بولین، لیست ها، دیکشنری ها.
18 | 2. **عملگر ها و ساختار های کنترلی**
19 | - عملگر های ریاضی، مقایسه ای و منطقی.
20 | - شرط (`if/elif/else`).
21 | - حلقه ها (`for`، `while`).
22 | 3. **توابع و ماژول ها**
23 | - تعریف توابع.
24 | - ورودی و خروجی توابع.
25 | - آشنایی با `import` و ساخت ماژول های سفارشی.
26 |
27 | ---
28 |
29 | ### [**فصل ۳: آشنایی با کتابخانه discord.py**](./saeson3.md)
30 | 1. **نصب و راه اندازی**
31 | - نصب کتابخانه با `pip install discord.py`.
32 | - تفاوت بین `discord.py` و `nextcord`.
33 | 2. **ساختار اصلی ربات**
34 | - کلاس `Bot` و `Intents`.
35 | - رویداد ها (`on_ready`، `on_message`).
36 |
37 | ---
38 |
39 | ### [**فصل ۴: ساخت اولین ربات**](./saeson4.md)
40 | 1. **اتصال به دیسکورد**
41 | - استفاده از توکن و اجرای ربات.
42 | 2. **پاسخ به پیام ها**
43 | - پردازش پیام های کاربران با `on_message`.
44 | - جلوگیری از پاسخ به بات های دیگر.
45 | 3. **ساخت دستورات ساده**
46 | - استفاده از پیشوند (مثلاً `!ping`).
47 |
48 | ---
49 |
50 | ### [**فصل ۵: کار با Embed ها و فایل ها**](./saeson5.md)
51 | 1. **ساخت Embed های زیبا**
52 | - استفاده از کلاس `Embed`.
53 | - افزودن فیلد ها، تصویر و فوتر.
54 | 2. **ارسال و دریافت فایل**
55 | - آپلود فایل به سرور دیسکورد.
56 | - دانلود فایل از پیام ها.
57 |
58 | ---
59 |
60 | ### [**فصل ۶: دستورات پیشرفته (Cog و Command)**](./saeson6.md)
61 | 1. **ساخت دستورات با `@commands.command`**
62 | - تعریف دستورات با پیشوند.
63 | - مدیریت خطا ها با `@commands.errors`.
64 | 2. **استفاده از Cog برای سازماندهی کد**
65 | - ایجاد کلاسهای Cog.
66 | - افزودن Cog به ربات.
67 |
68 | ---
69 |
70 | ### [**فصل ۷: دستورات اسلشی (Slash Commands)**](./saeson7.md)
71 | 1. **ثبت دستورات اسلشی**
72 | - استفاده از `@slash_command`.
73 | - همگام سازی دستورات با دیسکورد.
74 | 2. **پارامتر های دستورات**
75 | - دریافت ورودی از کاربر (متن، عدد، کاربر).
76 |
77 | ---
78 |
79 | ### [**فصل ۸: کار با دیتابیس**](./saeson8.md)
80 | 1. **ذخیره داده ها در JSON**
81 | - خواندن و نوشتن فایل های JSON.
82 | 2. **استفاده از SQLite**
83 | - اتصال به دیتابیس و اجرای کوئری ها.
84 | 3. **سیستم سطح بندی (XP System)**
85 | - ردیابی فعالیت کاربران و ذخیره داده ها.
86 |
87 | ---
88 |
89 | ### [**فصل ۹: مدیریت سرور و کاربران**](./saeson9.md)
90 | 1. **دستورات مدیریتی**
91 | - بن، میوت، پاک کردن پیام ها.
92 | 2. **کار با نقش ها (Roles)**
93 | - ایجاد، ویرایش و اختصاص نقش به کاربران.
94 |
95 | ---
96 |
97 | ### [**فصل ۱۰: استقرار ربات (Deploy)**](./saeson10.md)
98 | 1. **انتشار ربات روی سرور های ابری**
99 | - استفاده از Replit، Heroku یا Railway.
100 | 2. **اجرای ربات روی سرور لینوکس**
101 | - استفاده از PM2 یا systemd.
102 | 3. **امنیت و نگه داری**
103 | - پنهان کردن توکن با `.env`.
104 | - بروزرسانی کتابخانه ها.
105 |
106 | ---
107 |
108 | ### [**فصل ۱۱: پروژه های عملی**](./saeson11.md)
109 | 1. **ربات نظرسنجی**
110 | - استفاده از Reactions و تحلیل نتایج.
111 | 2. **ربات موزیک**
112 | - اتصال به چنل صوتی و پخش آهنگ.
113 | 3. **ربات مینی گیم**
114 | - بازی های ساده مثل سکه، شانس و جوایز.
115 |
116 | ---
117 |
118 | ### **ضمیمه ها و منابع بیشتر**
119 | - مستندات رسمی [discord.py](https://discordpy.readthedocs.io/).
120 | - لینک مخزن GitHub برای مثال های کد.
121 | - جامعه های پشتیبانی (سرور های دیسکورد، Stack Overflow).
122 |
123 | ---
124 |
125 | ### **نکات کلیدی برای آموزش:**
126 | - هر فصل با مثال های ساده و پروژه محور آموزش داده شود.
127 | - استفاده از تصاویر و نمودار برای توضیح مفاهیم پیچیده.
128 | - تمرین های عملی پس از هر درس برای تثبیت یادگیری.
129 | - تاکید بر اشکال زدایی (Debugging) و حل خطا های رایج.
--------------------------------------------------------------------------------
/python/per/saeson1.md:
--------------------------------------------------------------------------------
1 | **فصل ۱: مقدمه و آماده سازی محیط کار**
2 |
3 | ---
4 |
5 | ### **۱.۱ برنامه نویسی چیست؟**
6 | برنامه نویسی به معنای نوشتن دستورالعمل هایی است که کامپیوتر می تواند آن ها را اجرا کند تا یک خروجی یا عملکرد خاص ایجاد شود.
7 | - **چرا دیسکورد و پایتون؟**
8 | - **دیسکورد**: یک پلتفرم محبوب برای جوامع آنلاین است که امکان ساخت ربات های خودکار را فراهم می کند.
9 | - **پایتون**: یک زبان ساده و قدرتمند با کتابخانه های عالی مثل `discord.py` برای ساخت ربات های دیسکورد.
10 |
11 | ---
12 |
13 | ### **۱.۲ ابزار های مورد نیاز**
14 | برای شروع، به ابزار های زیر نیاز دارید:
15 |
16 | #### **۱.۲.۱ نصب پایتون و pip**
17 | 1. به سایت [Python.org](https://www.python.org) بروید.
18 | 2. نسخه **Python 3.10 یا بالاتر** را دانلود و نصب کنید.
19 | 3. هنگام نصب، گزینه **Add Python to PATH** را فعال کنید.
20 | 4. پس از نصب، ترمینال/CMD را باز کرده و دستورات زیر را بررسی کنید:
21 | ```bash
22 | python --version # باید نسخه پایتون نمایش داده شود (مثلاً Python 3.10.6)
23 | pip --version # باید نسخه pip نمایش داده شود (مثلاً pip 23.1.2)
24 | ```
25 |
26 | #### **۱.۲.۲ ویرایشگر کد: VS Code**
27 | - VS Code را از [این لینک](https://code.visualstudio.com) دانلود و نصب کنید.
28 | - پس از نصب، پکیج **Python Extension** را از بخش Extensions اضافه کنید.
29 |
30 | #### **۱.۲.۳ ساخت بات در دیسکورد**
31 | 1. به [پنل توسعه دهندگان دیسکورد](https://discord.com/developers/applications) بروید.
32 | 2. روی **New Application** کلیک کنید و نام ربات را وارد کنید.
33 | 3. به بخش **Bot** در منوی سمت چپ بروید و **Add Bot** را بزنید.
34 | 4. توکن (Token) ربات را کپی و در جای امن ذخیره کنید (مثل یک فایل موقت).
35 |
36 | 
37 | 
38 | 
39 | 
40 | 
41 | 
42 | 
43 | 
44 | 
45 |
46 | ---
47 |
48 | ### **۱.۳ نصب کتابخانه discord.py**
49 | در ترمینال/CMD دستور زیر را اجرا کنید:
50 | ```bash
51 | pip install discord.py
52 | ```
53 |
54 | #### **تفاوت discord.py و nextcord**:
55 | - `nextcord` یک فورک به روز تر از `discord.py` است که مشکلات نسخه اصلی را رفع کرده. برای نصب:
56 |
57 | ```bash
58 | pip install nextcord
59 | ```
60 |
61 | ---
62 |
63 | ### **۱.۴ ساخت اولین ربات**
64 | یک فایل پایتون با نام `bot.py` ایجاد کرده و کد زیر را در آن بنویسید:
65 |
66 | ```python
67 | import discord
68 | from discord.ext import commands
69 |
70 | # تنظیمات اولیه
71 | intents = discord.Intents.default()
72 | intents.message_content = True # برای دسترسی به محتوای پیام ها
73 |
74 | bot = commands.Bot(command_prefix='!', intents=intents)
75 |
76 | # رویداد آماده بودن ربات
77 | @bot.event
78 | async def on_ready():
79 | print(f'✅ ربات {bot.user.name} آنلاین شد!')
80 |
81 | # دستور ساده پینگ-پونگ
82 | @bot.command()
83 | async def ping(ctx):
84 | await ctx.reply(f'🏓 پونگ! تاخیر: {round(bot.latency * 1000)}ms')
85 |
86 | # اجرای ربات با توکن
87 | bot.run('TOKEN_خود_را_اینجا_قرار_دهید')
88 | ```
89 |
90 | ---
91 |
92 | ### **۱.۵ تست ربات**
93 | 1. توکن ربات را جایگزین `TOKEN_خود_را_اینجا_قرار_دهید` کنید.
94 | 2. ربات را با دستور زیر اجرا کنید:
95 |
96 | ```bash
97 | python bot.py
98 | ```
99 | 3. اگر همه چیز درست باشد، ربات در دیسکورد آنلاین می شود.
100 | 4. در سرور دیسکورد، دستور `!ping` را ارسال کنید تا پاسخ ربات را ببینید.
101 |
102 | ---
103 |
104 | ### **تمرین عملی فصل ۱**
105 | ۱. ربات خود را در دیسکورد ایجاد کرده و توکن آن را دریافت کنید.
106 | ۲. کد بالا را اجرا و مطمئن شوید ربات به دستور `!ping` پاسخ می دهد.
107 | ۳. دستور جدیدی مثل `!سلام` اضافه کنید که به کاربر خوش آمد بگوید.
108 |
109 | ---
110 |
111 | ### **مشکلات رایج**
112 | - **ربات آنلاین نمی شود**:
113 | - توکن را بررسی کنید.
114 | - اینترنت وصل است؟
115 | - کتابخانه `discord.py` نصب شده؟
116 |
117 | - **ربات به پیام ها پاسخ نمی دهد**:
118 | - `Intents.message_content` را فعال کنید.
119 | - ربات را به سرور اضافه کرده باشید.
120 |
121 | ---
122 |
123 | ### **نکات کلیدی**
124 | - **هرگز توکن ربات را در کد عمومی قرار ندهید** (در فصل های بعدی از `.env` استفاده خواهیم کرد).
125 | - برای دستورات پیشرفته تر، از `discord.ext.commands` استفاده کنید.
126 |
127 | ---
128 |
129 | **فصل بعدی**: مفاهیم پایه پایتون (متغیر ها، شرط ها، حلقه ها و توابع)! 🐍
--------------------------------------------------------------------------------
/python/per/saeson10.md:
--------------------------------------------------------------------------------
1 | **فصل ۱۰: استقرار ربات (Deploy)**
2 |
3 | ---
4 |
5 | ### **۱۰.۱ انتخاب پلتفرم استقرار**
6 | انتخاب پلتفرم مناسب بستگی به نیازهای پروژه دارد:
7 | - **سرور های ابری رایگان**: Replit, Railway, Heroku (مناسب برای پروژه های کوچک).
8 | - **سرور های اختصاصی**: VPS مانند DigitalOcean, AWS, Hetzner (برای ربات های حرفه ای).
9 | - **هاستینگ خصوصی**: اجرا روی رایانه شخصی با نرمافزارهایی مثل PM2 (فقط برای تست).
10 |
11 | ---
12 |
13 | ### **۱۰.۲ استقرار روی Replit (ساده ترین روش)**
14 | #### **مراحل**:
15 | ۱. ساخت پروژه جدید در [Replit](https://replit.com).
16 | ۲. آپلود فایل های پروژه (`main.py`, `requirements.txt` و ...).
17 | ۳. تنظیم **Secrets** (توکن ربات) در بخش **Environment Variables**.
18 | ۴. افزودن فایل `keep_alive.py` برای جلوگیری از خوابیدن ربات:
19 | ```python
20 | from flask import Flask
21 | from threading import Thread
22 |
23 | app = Flask('')
24 |
25 | @app.route('/')
26 | def home():
27 | return "Bot is alive!"
28 |
29 | def run():
30 | app.run(host='0.0.0.0', port=8080)
31 |
32 | def keep_alive():
33 | t = Thread(target=run)
34 | t.start()
35 | ```
36 |
37 | ۵. اجرای ربات:
38 | ```python
39 | keep_alive()
40 | bot.run(os.environ['TOKEN'])
41 | ```
42 |
43 | ---
44 |
45 | ### **۱۰.۳ استقرار روی سرور لینوکس (VPS)**
46 | #### **مراحل پایه برای اوبونتو**:
47 | ۱. **اتصال به سرور**:
48 |
49 | ```bash
50 | ssh root@IP_سرور
51 | ```
52 |
53 | ۲. **نصب پیش نیاز ها**:
54 |
55 | ```bash
56 | sudo apt update && sudo apt upgrade -y
57 | sudo apt install python3-pip python3-venv git -y
58 | ```
59 |
60 | ۳. **کپی کردن پروژه**:
61 |
62 | ```bash
63 | git clone https://github.com/نام-کاربری/ربات-شما.git
64 | cd ربات-شما
65 | ```
66 |
67 | ۴. **نصب وابستگی ها**:
68 | ```bash
69 | python3 -m venv venv
70 | source venv/bin/activate
71 | pip install -r requirements.txt
72 | ```
73 |
74 | ۵. **اجرای ربات با PM2**:
75 |
76 | ```bash
77 | npm install pm2 -g
78 | pm2 start "python3 main.py" --name "my-bot"
79 | pm2 save
80 | pm2 startup # ایجاد سرویس خودکار
81 | ```
82 |
83 | ---
84 |
85 | ### **۱۰.۴ استقرار روی Railway یا Heroku**
86 | #### **Railway**:
87 | ۱. ساخت پروژه جدید و اتصال به ریپازیتوری GitHub.
88 | ۲. تنظیم متغیر های محیطی (Environment Variables) در تب **Variables**.
89 | ۳. انتخاب پورت پیشفرض (`8000`) و فعالسازی **Deploy**.
90 |
91 | #### **Heroku**:
92 | ۱. ساخت اپلیکیشن جدید در [Heroku](https://heroku.com).
93 | ۲. تنظیم Buildpack:
94 | ```bash
95 | heroku buildpacks:set heroku/python
96 | ```
97 | ۳. افزودن فایل `Procfile`:
98 | ```bash
99 | worker: python3 main.py
100 | ```
101 | ۴. دپلوی کد از طریق Git:
102 | ```bash
103 | git push heroku main
104 | ```
105 |
106 | ---
107 |
108 | ### **۱۰.۵ امنیت در استقرار**
109 | #### **۱. مخفی سازی توکن**:
110 | - استفاده از فایل `.env`:
111 | ```env
112 | TOKEN = "مقدار_توکن"
113 | ```
114 | - خواندن در کد:
115 | ```python
116 | from dotenv import load_dotenv
117 | load_dotenv()
118 | bot.run(os.getenv('TOKEN'))
119 | ```
120 |
121 | #### **۲. فایروال و محدودیت IP**:
122 | ```bash
123 | sudo ufw allow 22 # SSH
124 | sudo ufw allow 80 # HTTP
125 | sudo ufw enable
126 | ```
127 |
128 | #### **۳. استفاده از Reverse Proxy (Nginx)**:
129 | ```nginx
130 | server {
131 | listen 80;
132 | server_name example.com;
133 |
134 | location / {
135 | proxy_pass http://localhost:8000;
136 | proxy_set_header Host $host;
137 | }
138 | }
139 | ```
140 |
141 | ---
142 |
143 | ### **۱۰.۶ نگه داری ربات**
144 | #### **۱. مانیتورینگ**:
145 |
146 | ```bash
147 | pm2 logs my-bot --lines 100 # نمایش ۱۰۰ خط آخر لاگ
148 | pm2 monit # مانیتورینگ لحظه ای
149 | ```
150 |
151 | #### **۲. بروزرسانی خودکار**:
152 | با استفاده از **Cron Jobs**:
153 | ```bash
154 | 0 3 * * * cd /path/to/bot && git pull && pm2 restart my-bot
155 | ```
156 |
157 | #### **۳. بکاپ گیری**:
158 |
159 | ```bash
160 | # بکاپ از دیتابیس SQLite
161 | cp database.db backup/database_$(date +%F).db
162 |
163 | # آپلود به فضای ابری (مثلاً AWS S3)
164 | aws s3 cp backup s3://my-bot-backups --recursive
165 | ```
166 |
167 | ---
168 |
169 | ### **تمرین عملی فصل ۱۰**
170 | ۱. ربات خود را روی Replit یا Railway مستقر کنید و مطمئن شوید ۲۴/۷ فعال است.
171 | ۲. با استفاده از PM2 ربات را روی یک سرور لینوکس اجرا کنید.
172 | ۳. یک سیستم بکاپ خودکار با Cron Jobs طراحی کنید.
173 |
174 | ---
175 |
176 | ### **مشکلات رایج**
177 | - **ربات بعد از مدتی قطع می شود**:
178 | - از PM2 یا سیستم های مشابه برای اجرای دائمی استفاده کنید.
179 | - بررسی کنید سرور منابع کافی (CPU/RAM) دارد.
180 | - **خطای `ImportError`**:
181 | - مطمئن شوید همه پکیج ها در `requirements.txt` لیست شده اند.
182 | - دستور `pip install -r requirements.txt` را اجرا کنید.
183 |
184 | ---
185 |
186 | ### **نکات طلایی**
187 | - برای ربات های بزرگ، از **Docker** برای مدیریت محیط ایزوله استفاده کنید.
188 | - همیشه قبل از آپدیت کد، از دیتابیس **بکاپ** بگیرید.
189 | - از **GitHub Actions** برای CI/CD (استقرار خودکار) استفاده کنید.
190 |
191 | ---
192 |
193 | **پایان دوره!** 🎉
194 | حالا شما می توانید ربات های دیسکورد حرفه ای بسازید، آن ها را توسعه دهید و در سرور های مختلف اجرا کنید. یادگیری را ادامه دهید و پروژه های خلاقانه خود را خلق کنید!
195 |
196 | **[پیشنهاد]** برای بهبود مهارت ها، سورس کد ربات های متن باز را در GitHub مطالعه کنید و در پروژه های مشارکتی شرکت نمایید!
--------------------------------------------------------------------------------
/python/per/saeson11.md:
--------------------------------------------------------------------------------
1 | **فصل ۱۱: پروژه های عملی برای تثبیت مهارت ها**
2 |
3 | ---
4 |
5 | ### **پروژه ۱: ربات نظرسنجی (Poll Bot)**
6 | **هدف**: ساخت رباتی که با دستور `/نظرسنجی` یک نظرسنجی با گزینه های دلخواه ایجاد کند و نتایج را تحلیل کند.
7 |
8 | #### **مراحل پیاده سازی**:
9 | ۱. **ثبت دستور اسلشی**:
10 |
11 | ```python
12 | @bot.tree.command(name="نظرسنجی", description="ایجاد نظرسنجی")
13 | @app_commands.describe(سوال="متن سوال", گزینه_ها="گزینه ها (با ویرگول جدا کنید)")
14 | async def نظرسنجی(interaction: discord.Interaction, سوال: str, گزینه_ها: str):
15 | options = [opt.strip() for opt in گزینه_ها.split(",")]
16 | ```
17 |
18 | ۲. **ساخت Embed و افزودن Reactions**:
19 |
20 | ```python
21 | embed = discord.Embed(title=سوال, color=0x5865F2)
22 | for i, option in enumerate(options):
23 | embed.add_field(name=f"گزینه {i+1}", value=option, inline=False)
24 |
25 | poll_msg = await interaction.channel.send(embed=embed)
26 | for emoji in ["1️⃣", "2️⃣", "3️⃣", "4️⃣"]:
27 | await poll_msg.add_reaction(emoji)
28 | ```
29 |
30 | ---
31 |
32 | ### **پروژه ۲: ربات موزیک (Music Bot)**
33 | **هدف**: ساخت رباتی که به کانال صوتی متصل شود و آهنگ از یوتیوب پخش کند.
34 |
35 | #### **مراحل پیاده سازی**:
36 | ۱. **نصب کتابخانه های مورد نیاز**:
37 | ```bash
38 | pip install yt-dlp discord.py[voice]
39 | ```
40 |
41 | ۲. **اتصال به کانال صوتی و پخش آهنگ**:
42 |
43 | ```python
44 | @bot.command()
45 | async def پخش(ctx, url: str):
46 | voice_channel = ctx.author.voice.channel
47 | voice_client = await voice_channel.connect()
48 |
49 | ydl_opts = {"format": "bestaudio"}
50 | with yt_dlp.YoutubeDL(ydl_opts) as ydl:
51 | info = ydl.extract_info(url, download=False)
52 | audio_url = info["url"]
53 |
54 | voice_client.play(discord.FFmpegPCMAudio(audio_url))
55 | await ctx.send(f"🎶 در حال پخش: **{info['title']}**")
56 | ```
57 |
58 | ---
59 |
60 | ### **پروژه ۳: سیستم سطح بندی (XP System)**
61 | **هدف**: ساخت سیستمی که فعالیت کاربران را ردیابی کند و بر اساس XP به آن ها سطح اختصاص دهد.
62 |
63 | #### **مراحل پیاده سازی**:
64 | ۱. **ذخیره داده ها در SQLite**:
65 | ```python
66 | async def update_xp(user_id: int):
67 | async with aiosqlite.connect("xp.db") as db:
68 | await db.execute("""
69 | INSERT INTO users (user_id, xp)
70 | VALUES (?, 10)
71 | ON CONFLICT(user_id) DO UPDATE SET xp = xp + 10
72 | """, (user_id,))
73 | await db.commit()
74 | ```
75 |
76 | ۲. **بررسی ارتقا سطح**:
77 |
78 | ```python
79 | @bot.event
80 | async def on_message(message):
81 | if message.author.bot:
82 | return
83 | await update_xp(message.author.id)
84 | user_xp = await get_xp(message.author.id)
85 | if user_xp >= 100:
86 | await message.channel.send(f"🎉 {message.author.mention} به سطح جدید رسید!")
87 | ```
88 |
89 | ---
90 |
91 | ### **پروژه ۴: سیستم تیکت (Ticket System)**
92 | **هدف**: ساخت سیستمی که کاربران با دستور `/تیکت` یک کانال خصوصی برای پشتیبانی ایجاد کنند.
93 |
94 | #### **مراحل پیاده سازی**:
95 | ۱. **ساخت کانال تیکت**:
96 |
97 | ```python
98 | @bot.tree.command(name="تیکت", description="ایجاد تیکت پشتیبانی")
99 | async def تیکت(interaction: discord.Interaction):
100 | overwrites = {
101 | interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),
102 | interaction.user: discord.PermissionOverwrite(read_messages=True)
103 | }
104 | ticket_channel = await interaction.guild.create_text_channel(
105 | name=f"تیکت-{interaction.user.name}",
106 | overwrites=overwrites
107 | )
108 | await ticket_channel.send(f"📩 {interaction.user.mention} تیکت شما ایجاد شد!")
109 | ```
110 |
111 | ---
112 |
113 | ### **پروژه ۵: ربات مینی گیم (سکه، شانس، جوایز)**
114 | **هدف**: ساخت بازی های ساده برای تعامل با کاربران.
115 |
116 | #### **دستورات پیشنهادی**:
117 | ۱. **سکه**:
118 |
119 | ```python
120 | @bot.command()
121 | async def سکه(ctx):
122 | result = random.choice(["رو", "پشت"])
123 | await ctx.send(f"🪙 نتیجه: **{result}**")
124 | ```
125 |
126 | ۲. **شماره تصادفی**:
127 |
128 | ```python
129 | @bot.command()
130 | async def شماره(ctx, حداقل: int, حداکثر: int):
131 | num = random.randint(حداقل, حداکثر)
132 | await ctx.send(f"🎲 شماره تصادفی: **{num}**")
133 | ```
134 |
135 | ---
136 |
137 | ### **تمرین های تکمیلی**:
138 | ۱. **ربات آب وهوا**:
139 | - با دستور `/آبوهوا [شهر]` اطلاعات آب وهوا را از API دریافت و نمایش دهید.
140 |
141 | ۲. **ربات واژه یاب**:
142 | - با دستور `/معنی [کلمه]` معنی کلمه را از فرهنگ نامه آنلاین استخراج کنید.
143 |
144 | ۳. **ربات اقتصاد مجازی**:
145 | - کاربران با دستورات `!کار` و `!خرید` سکه مجازی جمع آوری کنند و آیتم بخرند.
146 |
147 | ---
148 |
149 | ### **مشکلات رایج و راه حل ها**:
150 | - **ربات به Reactions پاسخ نمی دهد**:
151 | - مطمئن شوید `on_raw_reaction_add` را پیاده سازی کرده اید.
152 | - Intent های لازم (مثلاً `Intents.reactions`) را فعال کنید.
153 | - **خطای صدا در ربات موزیک**:
154 | - FFmpeg را نصب کنید (`sudo apt install ffmpeg`).
155 | - از `discord.FFmpegPCMAudio` بهدرستی استفاده کنید.
156 |
157 | ---
158 |
159 | ### **نکات پایانی**:
160 | - پروژه ها را به صورت **ماژولار** و در فایل های جداگانه سازماندهی کنید.
161 | - از **GitHub** برای مدیریت نسخه ها و همکاری تیمی استفاده کنید.
162 | - برای ایده های بیشتر، به [Awesome Discord Bots](https://github.com/meew0/discord-bot-best-practices) مراجعه کنید.
163 |
164 | ---
165 |
166 | **موفق باشید!** 🚀
167 | با تکمیل این پروژه ها، شما حالا یک توسعه دهنده حرفه ای ربات های دیسکورد هستید. به جامعه توسعه دهندگان بپیوندید و ایده های خود را به واقعیت تبدیل کنید!
--------------------------------------------------------------------------------
/python/per/saeson2.md:
--------------------------------------------------------------------------------
1 | **فصل ۲: آشنایی با مفاهیم پایه پایتون**
2 |
3 | ---
4 |
5 | ### **۲.۱ متغیر ها و انواع داده**
6 | متغیر ها مانند جعبه هایی هستند که داده ها را ذخیره می کنند. در پایتون نیازی به تعیین نوع متغیر نیست (پویا بودن نوع داده).
7 |
8 | #### **انواع داده اصلی**:
9 | - **رشته (String)**:
10 |
11 | ```python
12 | name = "آلیس" # متن درون "" یا '' قرار می گیرد
13 | message = 'سلام!'
14 | ```
15 |
16 | - **عدد (Integer و Float)**:
17 |
18 | ```python
19 | age = 20 # عدد صحیح
20 | price = 12.5 # عدد اعشاری
21 | ```
22 |
23 | - **بولین (Boolean)**:
24 |
25 | ```python
26 | is_online = True
27 | has_permission = False
28 | ```
29 |
30 | - **لیست (List)**:
31 |
32 | ```python
33 | users = ["آلیس", "بابک", "چارلی"]
34 | print(users[0]) # خروجی: آلیس
35 | ```
36 |
37 | - **دیکشنری (Dictionary)**:
38 |
39 | ```python
40 | user = {
41 | "name": "آلیس",
42 | "age": 25,
43 | "is_admin": True
44 | }
45 | print(user["name"]) # خروجی: آلیس
46 | ```
47 |
48 | ---
49 |
50 | ### **۲.۲ عملگر ها**
51 | #### **عملگر های ریاضی**:
52 |
53 | ```python
54 | a = 10 + 5 # 15
55 | b = 20 - 3 # 17
56 | c = 6 * 2 # 12
57 | d = 10 / 2 # 5.0 (تقسیم اعشاری)
58 | e = 10 // 3 # 3 (تقسیم صحیح)
59 | f = 10 % 3 # 1 (باقی مانده)
60 | ```
61 |
62 | #### **عملگر های مقایسه ای**:
63 |
64 | ```python
65 | print(5 > 3) # True
66 | print(5 == 5) # True
67 | print(5 != 3) # True
68 | ```
69 |
70 | #### **عملگر های منطقی**:
71 |
72 | ```python
73 | has_account = True
74 | is_logged_in = False
75 | print(has_account and is_logged_in) # False
76 | print(has_account or is_logged_in) # True
77 | print(not has_account) # False
78 | ```
79 |
80 | ---
81 |
82 | ### **۲.۳ ساختار های کنترلی**
83 | #### **شرط `if/elif/else`**:
84 |
85 | ```python
86 | hour = 14
87 | if hour < 12:
88 | print("صبح بخیر!")
89 | elif hour < 18:
90 | print("عصر بخیر!")
91 | else:
92 | print("شب بخیر!")
93 | ```
94 |
95 | #### **حلقه `for`**:
96 | ```python
97 | for i in range(5): # اعداد ۰ تا ۴
98 | print(i)
99 |
100 | for user in ["آلیس", "بابک", "چارلی"]:
101 | print(f"سلام {user}!")
102 | ```
103 |
104 | #### **حلقه `while`**:
105 |
106 | ```python
107 | count = 3
108 | while count > 0:
109 | print(count)
110 | count -= 1 # کاهش مقدار count در هر دور
111 | ```
112 |
113 | ---
114 |
115 | ### **۲.۴ توابع (Functions)**
116 | توابع بلوک هایی از کد هستند که یک کار خاص انجام می دهند.
117 |
118 | #### **تعریف تابع ساده**:
119 |
120 | ```python
121 | def greet(name):
122 | return f"سلام {name}!"
123 |
124 | print(greet("آلیس")) # خروجی: سلام آلیس!
125 | ```
126 |
127 | #### **پارامتر های پیشفرض**:
128 |
129 | ```python
130 | def multiply(a, b=2):
131 | return a * b
132 |
133 | print(multiply(5)) # 10 (b=2 استفاده می شود)
134 | print(multiply(5, 3)) # 15
135 | ```
136 |
137 | ---
138 |
139 | ### **۲.۵ ماژول ها (Modules)**
140 | ماژول ها فایل های پایتون هستند که توابع و متغیر ها را سازماندهی می کنند.
141 |
142 | #### **ساخت ماژول سفارشی**:
143 | - فایل `math_utils.py`:
144 |
145 | ```python
146 | PI = 3.14
147 |
148 | def square(x):
149 | return x ** 2
150 | ```
151 |
152 | - استفاده در فایل اصلی:
153 |
154 | ```python
155 | import math_utils
156 |
157 | print(math_utils.PI) # 3.14
158 | print(math_utils.square(4)) # 16
159 | ```
160 |
161 | ---
162 |
163 | ### **تمرین عملی فصل ۲**
164 | ۱. تابعی بنویسید که دو عدد بگیرد و عدد بزرگتر را برگرداند.
165 | ۲. لیستی از نام کاربران بسازید و با حلقه `for` به همه سلام کنید.
166 | ۳. دیکشنری برای ذخیره اطلاعات کاربر (نام، سن، ایمیل) ایجاد کنید.
167 |
168 | **مثال تمرین ۱**:
169 |
170 | ```python
171 | def find_max(a, b):
172 | return a if a > b else b
173 |
174 | print(find_max(10, 5)) # 10
175 | ```
176 |
177 | ---
178 |
179 | ### **نکات مهم**
180 | - نام متغیر ها باید توصیفی و به انگلیسی باشد (مثال: `user_age` به جای `a`).
181 | - از توابع برای سازماندهی کد و جلوگیری از تکرار استفاده کنید.
182 | - برای خطایابی از `print()` یا ابزار های دیباگ در VS Code استفاده کنید.
183 |
184 | ---
185 |
186 | **فصل بعدی**: شروع کار با کتابخانه `discord.py` و ساخت اولین ربات! 🚀
--------------------------------------------------------------------------------
/python/per/saeson3.md:
--------------------------------------------------------------------------------
1 | **فصل ۳: آشنایی با کتابخانه `discord.py`**
2 |
3 | ---
4 |
5 | ### **۳.۱ معرفی کتابخانه `discord.py`**
6 | `discord.py` یک کتابخانه قدرتمند و انعطاف پذیر پایتون برای ساخت ربات های دیسکورد است. این کتابخانه با ارائه ابزار های ساده، امکان تعامل با API دیسکورد را فراهم می کند.
7 |
8 | #### **چرا `discord.py`؟**
9 | - **ساده و مبتدی پسند**: نحو (Syntax) تمیز و قابل فهم.
10 | - **کاملاً غیر همزمان (Async)**: عملکرد بهینه برای پردازش چند کاره.
11 | - **مستندات عالی**: [مستندات رسمی](https://discordpy.readthedocs.io/) با مثال های کاربردی.
12 |
13 | ---
14 |
15 | ### **۳.۲ نصب و راه اندازی**
16 | #### **نصب کتابخانه**:
17 | در ترمینال/CMD دستور زیر را اجرا کنید:
18 | ```bash
19 | pip install discord.py
20 | ```
21 |
22 | #### **نسخه های جایگزین**:
23 | - **nextcord**: فورکی از `discord.py` با پشتیبانی بهتر و آپدیت های منظم.
24 | ```bash
25 | pip install nextcord
26 | ```
27 |
28 | ---
29 |
30 | ### **۳.۳ ساختار اصلی یک ربات**
31 | #### **۱. ایمپورت ماژول ها**:
32 | ```python
33 | import discord
34 | from discord.ext import commands
35 | ```
36 |
37 | #### **۲. تنظیم Intents**:
38 | اینت ها دسترسی های ربات به رویداد های دیسکورد را مشخص می کنند.
39 |
40 | ```python
41 | intents = discord.Intents.default()
42 | intents.message_content = True # دسترسی به محتوای پیام ها
43 | ```
44 |
45 | #### **۳. ایجاد نمونه ربات**:
46 | ```python
47 | bot = commands.Bot(
48 | command_prefix='!', # پیشوند دستورات (مثلاً !ping)
49 | intents=intents
50 | )
51 | ```
52 |
53 | ---
54 |
55 | ### **۳.۴ رویداد ها (Events)**
56 | رویداد ها برای پاسخ به اتفاقاتی مانند آنلاین شدن ربات یا دریافت پیام استفاده می شوند.
57 |
58 | #### **رویداد `on_ready`**:
59 | وقتی ربات با موفقیت به دیسکورد متصل شود.
60 | ```python
61 | @bot.event
62 | async def on_ready():
63 | print(f'✅ {bot.user.name} آنلاین شد!')
64 | ```
65 |
66 | #### **رویداد `on_message`**:
67 | هر بار که پیامی در سرور ارسال می شود.
68 |
69 | ```python
70 | @bot.event
71 | async def on_message(message):
72 | if message.author == bot.user: # جلوگیری از پاسخ به خود ربات
73 | return
74 |
75 | if message.content == 'سلام':
76 | await message.channel.send('سلام! چطوری؟ 😊')
77 |
78 | await bot.process_commands(message) # پردازش دستورات
79 | ```
80 |
81 | ---
82 |
83 | ### **۳.۵ دستورات ساده (Commands)**
84 | با استفاده از `@commands.command()` می توانید دستورات سفارشی ایجاد کنید.
85 |
86 | #### **دستور `ping`**:
87 |
88 | ```python
89 | @bot.command()
90 | async def ping(ctx):
91 | latency = round(bot.latency * 1000) # تاخیر ربات به میلی ثانیه
92 | await ctx.reply(f'🏓 پونگ! تاخیر: {latency}ms')
93 | ```
94 |
95 | #### **پارامتر های دستور**:
96 |
97 | ```python
98 | @bot.command()
99 | async def say(ctx, *, text):
100 | await ctx.send(text) # دستور !say Hello World
101 | ```
102 |
103 | ---
104 |
105 | ### **۳.۶ کار با Embed ها**
106 | Embed ها پیام های ساختار یافته و زیبا برای نمایش اطلاعات هستند.
107 |
108 | #### **ارسال Embed**:
109 |
110 | ```python
111 | @bot.command()
112 | async def info(ctx):
113 | embed = discord.Embed(
114 | title="عنوان Embed",
115 | description="توضیحات کلی",
116 | color=discord.Color.blue()
117 | )
118 | embed.add_field(name="فیلد ۱", value="مقدار ۱", inline=False)
119 | embed.set_thumbnail(url=ctx.author.avatar.url)
120 |
121 | await ctx.send(embed=embed)
122 | ```
123 |
124 | ---
125 |
126 | ### **مثال کامل ربات**:
127 |
128 | ```python
129 | import discord
130 | from discord.ext import commands
131 |
132 | intents = discord.Intents.default()
133 | intents.message_content = True
134 |
135 | bot = commands.Bot(command_prefix='!', intents=intents)
136 |
137 | @bot.event
138 | async def on_ready():
139 | print(f'✅ {bot.user} آنلاین شد!')
140 |
141 | @bot.command()
142 | async def ping(ctx):
143 | await ctx.reply(f'🏓 پونگ! تاخیر: {round(bot.latency * 1000)}ms')
144 |
145 | bot.run('TOKEN_خود_را_اینجا_قرار_دهید')
146 | ```
147 |
148 | ---
149 |
150 | ### **تمرین عملی فصل ۳**
151 | ۱. رباتی بسازید که با دستور `!ساعت` زمان فعلی را ارسال کند.
152 | ۲. Embed ی طراحی کنید که اطلاعات کاربر (نام، آیدی، تاریخ عضویت) را نمایش دهد.
153 | ۳. دستوری بسازید که با `!جمع 5 10` مجموع دو عدد را محاسبه کند.
154 |
155 | ---
156 |
157 | ### **مشکلات رایج**
158 | - **ربات به پیام ها پاسخ نمی دهد**:
159 | - مطمئن شوید `intents.message_content = True` است.
160 | - دستورات را با پیشوند صحیح (!) ارسال کنید.
161 | - **خطای `Missing Intents`**:
162 | - در [پنل توسعه دهندگان دیسکورد](https://discord.com/developers/applications)، اینت های لازم را فعال کنید.
163 |
164 | ---
165 |
166 | ### **نکات کلیدی**
167 | - **توکن ربات را در کد عمومی قرار ندهید** (در فصل های بعدی از `.env` استفاده می کنیم).
168 | - برای دستورات پیچیده تر از `Cog` استفاده کنید (فصل ۶).
169 | - همیشه قبل از اجرای ربات، کتابخانه ها را آپدیت کنید:
170 | ```bash
171 | pip install --upgrade discord.py
172 | ```
173 |
174 | ---
175 |
176 | **فصل بعدی**: ساخت اولین ربات دیسکورد با دستورات پیشرفته تر! 🚀
--------------------------------------------------------------------------------
/python/per/saeson4.md:
--------------------------------------------------------------------------------
1 | **فصل ۴: ساخت اولین ربات**
2 |
3 | ---
4 |
5 | ### **۴.۱ تنظیمات اولیه ربات**
6 | #### **۱. ایجاد فایل `main.py`**:
7 |
8 | ```python
9 | import discord
10 | from discord.ext import commands
11 | import datetime
12 |
13 | intents = discord.Intents.default()
14 | intents.message_content = True
15 |
16 | bot = commands.Bot(
17 | command_prefix="!",
18 | intents=intents,
19 | help_command=None # غیرفعال کردن دستور help پیشفرض
20 | )
21 | ```
22 |
23 | #### **۲. افزودن رویداد `on_ready`**:
24 |
25 | ```python
26 | @bot.event
27 | async def on_ready():
28 | print(f"✅ {bot.user.name} با موفقیت آنلاین شد!")
29 | print(f"تعداد سرور ها: {len(bot.guilds)}")
30 | print(f"زمان آنلاین شدن: {datetime.datetime.now()}")
31 | ```
32 |
33 | ---
34 |
35 | ### **۴.۲ ساخت دستورات پایه**
36 | #### **۱. دستور `!سلام`**:
37 |
38 | ```python
39 | @bot.command()
40 | async def سلام(ctx):
41 | await ctx.reply(f"سلام {ctx.author.mention}! 😊")
42 | ```
43 |
44 | #### **۲. دستور `!ساعت`**:
45 |
46 | ```python
47 | @bot.command()
48 | async def ساعت(ctx):
49 | now = datetime.datetime.now().strftime("%H:%M:%S")
50 | await ctx.send(f"🕒 ساعت فعلی: **{now}**")
51 | ```
52 |
53 | #### **۳. دستور `!جمع` با پارامتر**:
54 |
55 | ```python
56 | @bot.command()
57 | async def جمع(ctx, num1: int, num2: int):
58 | result = num1 + num2
59 | await ctx.send(f"نتیجه: `{num1} + {num2} = {result}`")
60 | ```
61 |
62 | ---
63 |
64 | ### **۴.۳ ارسال Embed های پیشرفته**
65 | #### **دستور `!کاربر`**:
66 |
67 | ```python
68 | @bot.command()
69 | async def کاربر(ctx, member: discord.Member = None):
70 | member = member or ctx.author # اگر کاربری منشن نشد، خود فرستنده در نظر گرفته می شود
71 |
72 | embed = discord.Embed(
73 | title=f"ℹ️ اطلاعات {member.name}",
74 | color=discord.Color.green()
75 | )
76 | embed.set_thumbnail(url=member.avatar.url)
77 | embed.add_field(name="تگ", value=member.mention)
78 | embed.add_field(name="آیدی", value=member.id)
79 | embed.add_field(name="تاریخ عضویت", value=member.joined_at.strftime("%Y/%m/%d"))
80 |
81 | await ctx.send(embed=embed)
82 | ```
83 |
84 | ---
85 |
86 | ### **۴.۴ مدیریت خطا ها**
87 | #### **خطای Missing Permissions**:
88 |
89 | ```python
90 | @bot.event
91 | async def on_command_error(ctx, error):
92 | if isinstance(error, commands.MissingPermissions):
93 | await ctx.send("⛔ شما دسترسی لازم را ندارید!")
94 | ```
95 |
96 | #### **خطای Missing Required Argument**:
97 |
98 | ```python
99 | @جمع.error
100 | async def جمع_خطا(ctx, error):
101 | if isinstance(error, commands.MissingRequiredArgument):
102 | await ctx.send("⚠️ لطفاً دو عدد وارد کنید!\nمثال: `!جمع 5 10`")
103 | ```
104 |
105 | ---
106 |
107 | ### **۴.۵ افزودن سیستم Help سفارشی**
108 |
109 | ```python
110 | @bot.command()
111 | async def کمک(ctx):
112 | embed = discord.Embed(
113 | title="📚 لیست دستورات",
114 | description="پیشوند دستورات: `!`",
115 | color=discord.Color.blue()
116 | )
117 | embed.add_field(
118 | name="عمومی",
119 | value="`سلام` `ساعت` `کاربر [@منشن]`",
120 | inline=False
121 | )
122 | embed.add_field(
123 | name="محاسباتی",
124 | value="`جمع <عدد1> <عدد2>`",
125 | inline=False
126 | )
127 |
128 | await ctx.send(embed=embed)
129 | ```
130 |
131 | ---
132 |
133 | ### **۴.۶ اجرای ربات**
134 |
135 | ```python
136 | # توکن را از فایل .env بخوانید (در فصل ۷ آموزش داده می شود)
137 | TOKEN = "TOKEN_خود_را_اینجا_قرار_دهید"
138 |
139 | if __name__ == "__main__":
140 | bot.run(TOKEN)
141 | ```
142 |
143 | ---
144 |
145 | ### **تمرین عملی فصل ۴**
146 | ۱. دستوری بسازید که با `!سکه` تصادفی رو یا پشت برگرداند.
147 | ۲. دستور `!پاککن` ایجاد کنید که تعداد مشخصی پیام پاک کند (نیاز به دسترسی مدیریت پیام ها).
148 | ۳. سیستمی طراحی کنید که هنگام جوین دادن کاربر به سرور، پیام خوش آمد گویی ارسال شود.
149 |
150 | **مثال تمرین ۳**:
151 |
152 | ```python
153 | @bot.event
154 | async def on_member_join(member):
155 | channel = member.guild.system_channel
156 | await channel.send(f"🎉 {member.mention} به سرور ما خوش آمدی!")
157 | ```
158 |
159 | ---
160 |
161 | ### **مشکلات رایج و راه حل ها**
162 | - **دستورات اجرا نمی شوند**:
163 | - مطمئن شوید `intents.message_content = True` است.
164 | - ربات را دوباره راه اندازی کنید (`Ctrl+C` و `python main.py`).
165 | - **ربات نمی تواند کاربران را منشن کند**:
166 | - در پنل توسعه دهندگان دیسکورد، **Server Members Intent** را فعال کنید.
167 |
168 | ---
169 |
170 | ### **نکات کلیدی**
171 | - همیشه از `ctx.reply()` به جای `ctx.send()` برای اشاره به کاربر استفاده کنید.
172 | - برای دریافت اطلاعات کاربران، از `discord.Member` به عنوان پارامتر استفاده کنید.
173 | - خطا ها را با `@bot.event` و `on_command_error` مدیریت کنید.
174 |
175 | ---
176 |
177 | **فصل بعدی**: کار با Embed ها، فایل ها و Attachment ها! 🚀
--------------------------------------------------------------------------------
/python/per/saeson5.md:
--------------------------------------------------------------------------------
1 | **فصل ۵: کار با Embed ها و فایل ها**
2 |
3 | ---
4 |
5 | ### **۵.۱ ساخت Embed های حرفه ای**
6 | Embed ها پیام های ساختار یافته ای هستند که اطلاعات را به شکل زیبا و سازماندهی شده نمایش می دهند.
7 |
8 | #### **ساخت یک Embed ساده**:
9 |
10 | ```python
11 | from discord import Embed
12 |
13 | @bot.command()
14 | async def اطلاع(ctx):
15 | embed = Embed(
16 | title="📢 اطلاعیه مهم",
17 | description="به سرور ما خوش آمدید!",
18 | color=0x00FF00 # کد HEX رنگ (سبز)
19 | )
20 | embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar.url)
21 | await ctx.send(embed=embed)
22 | ```
23 |
24 | #### **افزودن فیلد ها و تصویر**:
25 |
26 | ```python
27 | @bot.command()
28 | async def پروفایل(ctx, member: discord.Member = None):
29 | member = member or ctx.author
30 |
31 | embed = Embed(
32 | title=f"📁 پروفایل {member.name}",
33 | color=discord.Color.blurple()
34 | )
35 | embed.set_thumbnail(url=member.avatar.url)
36 | embed.add_field(name="تاریخ عضویت", value=member.joined_at.strftime("%Y/%m/%d"), inline=False)
37 | embed.add_field(name="تعداد نقش ها", value=len(member.roles), inline=True)
38 | embed.set_image(url="https://example.com/banner.png") # بنر پایین Embed
39 |
40 | await ctx.send(embed=embed)
41 | ```
42 |
43 | ---
44 |
45 | ### **۵.۲ ارسال و دریافت فایل**
46 | #### **۱. ارسال فایل از کامپیوتر**:
47 |
48 | ```python
49 | @bot.command()
50 | async def عکس(ctx):
51 | file = discord.File("path/to/image.jpg", filename="image.jpg")
52 | await ctx.send(file=file)
53 | ```
54 |
55 | #### **۲. ارسال فایل از اینترنت**:
56 |
57 | ```python
58 | import aiohttp
59 |
60 | @bot.command()
61 | async دانلود(ctx, url: str):
62 | async with aiohttp.ClientSession() as session:
63 | async with session.get(url) as resp:
64 | if resp.status == 200:
65 | data = await resp.read()
66 | file = discord.File(BytesIO(data), filename="download.png")
67 | await ctx.send(file=file)
68 | ```
69 |
70 | #### **۳. ذخیره فایل های ارسالی کاربران**:
71 |
72 | ```python
73 | @bot.event
74 | async def on_message(message):
75 | if message.attachments:
76 | attachment = message.attachments[0]
77 | await attachment.save(f"downloads/{attachment.filename}")
78 | await message.channel.send("✅ فایل ذخیره شد!")
79 | ```
80 |
81 | ---
82 |
83 | ### **۵.۳ ترکیب Embed و فایل**
84 | می توانید همزمان Embed و فایل ارسال کنید:
85 |
86 | ```python
87 | @bot.command()
88 | async def کارت(ctx):
89 | embed = Embed(title="🎴 کارت ویژه", color=0xFFD700)
90 | embed.set_image(url="attachment://card.png") # اشاره به فایل آپلود شده
91 |
92 | file = discord.File("images/card.png", filename="card.png")
93 | await ctx.send(embed=embed, file=file)
94 | ```
95 |
96 | ---
97 |
98 | ### **۵.۴ Embed های پویا با دینامیک داده**
99 | #### **مثال: نمایش اطلاعات سرور**:
100 |
101 | ```python
102 | @bot.command()
103 | async def سرور(ctx):
104 | guild = ctx.guild
105 | embed = Embed(title=guild.name, description=guild.description)
106 | embed.add_field(name="اعضا", value=guild.member_count)
107 | embed.add_field(name="مالک", value=guild.owner.mention)
108 | embed.set_thumbnail(url=guild.icon.url)
109 |
110 | await ctx.send(embed=embed)
111 | ```
112 |
113 | ---
114 |
115 | ### **تمرین عملی فصل ۵**
116 | ۱. دستوری بسازید که با `!میم [متن]` یک تصویر پیشفرض را دانلود و متن کاربر را روی آن بنویسد (با کتابخانه `PIL`).
117 | ۲. سیستمی طراحی کنید که هنگام ارسال عکس توسط کاربر، آن را در Embed نمایش دهد.
118 | ۳. دستور `!آمار` ایجاد کنید که تعداد پیام های کاربر را در Embed نمایش دهد.
119 |
120 | ---
121 |
122 | ### **مشکلات رایج**
123 | - **فایل ارسال نمی شود**:
124 | - مطمئن شوید مسیر فایل صحیح است.
125 | - از پسوند فایل (مثلاً `.jpg`) در `filename` استفاده کنید.
126 | - **تصویر در Embed نمایش داده نمی شود**:
127 | - از `attachment://filename.extension` در `set_image` استفاده کنید.
128 | - فایل را حتماً به پیام ضمیمه کنید.
129 |
130 | ---
131 |
132 | ### **نکات کلیدی**
133 | - برای رنگ Embedها می توانید از کد HEX یا رنگ های پیشفرض (`discord.Color.red()`) استفاده کنید.
134 | - حداکثر اندازه فایل آپلودی در دیسکورد **۸ مگابایت** است.
135 | - برای پردازش تصاویر، از کتابخانه `pillow` استفاده کنید:
136 | ```bash
137 | pip install pillow
138 | ```
139 |
140 | ---
141 |
142 | **فصل بعدی**: سازماندهی کد با Cog و ساخت دستورات پیشرفته تر! 🛠️
--------------------------------------------------------------------------------
/python/per/saeson6.md:
--------------------------------------------------------------------------------
1 | **فصل ۶: دستورات پیشرفته (Cog و Command)**
2 |
3 | ---
4 |
5 | ### **۶.۱ معرفی Cog (ماژول های سازماندهی کد)**
6 | Cog ها کلاس هایی هستند که دستورات، رویداد ها و تنظیمات ربات را **مدولار** می کنند و مدیریت کد را آسانتر می کنند.
7 |
8 | #### **مزایای استفاده از Cog**:
9 | - کد تمیز و قابل نگه داری
10 | - امکان بارگذاری/لغو بارگذاری دستورات بدون ری استارت ربات
11 | - مدیریت خطا ها به صورت جداگانه
12 |
13 | ---
14 |
15 | ### **۶.۲ ساخت اولین Cog**
16 | #### **۱. ساخت فایل `cogs/moderate.py`**:
17 |
18 | ```python
19 | from discord.ext import commands
20 |
21 | class Moderate(commands.Cog):
22 | def __init__(self, bot):
23 | self.bot = bot
24 |
25 | # دستور پاک کردن پیام ها
26 | @commands.command()
27 | @commands.has_permissions(manage_messages=True)
28 | async def پاککن(self, ctx, limit: int = 10):
29 | await ctx.channel.purge(limit=limit + 1) # +1 برای حذف خود دستور
30 | msg = await ctx.send(f"✅ {limit} پیام پاک شد!", delete_after=5)
31 |
32 | # خطای دسترسی
33 | @پاککن.error
34 | async def پاککن_خطا(self, ctx, error):
35 | if isinstance(error, commands.MissingPermissions):
36 | await ctx.send("⛔ شما دسترسی مدیریت پیام ها را ندارید!")
37 |
38 | # تابع ضروری برای لود Cog
39 | async def setup(bot):
40 | await bot.add_cog(Moderate(bot))
41 | ```
42 |
43 | #### **۲. لود کردن Cog در فایل اصلی**:
44 |
45 | ```python
46 | # در main.py
47 | async def main():
48 | await bot.load_extension("cogs.moderate")
49 |
50 | if __name__ == "__main__":
51 | bot.run(TOKEN)
52 | ```
53 |
54 | ---
55 |
56 | ### **۶.۳ دستورات پیشرفته با Decoratorها**
57 | #### **۱. دسترسی های کاربر (Permissions)**:
58 |
59 | ```python
60 | @commands.has_role("Admin") # نیاز به نقش خاص
61 | @commands.has_permissions(kick_members=True) # نیاز به دسترسی
62 | @commands.is_owner() # فقط مالک ربات
63 | ```
64 |
65 | #### **۲. محدودیت استفاده از دستورات**:
66 |
67 | ```python
68 | @commands.cooldown(rate=1, per=30, type=commands.BucketType.user) # 30 ثانیه کولدان
69 | async def جوایز(ctx):
70 | await ctx.send("🎉 شما 100 سکه دریافت کردید!")
71 | ```
72 |
73 | #### **۳. دستورات هیبریدی (Slash + Prefix)**:
74 |
75 | ```python
76 | from discord import app_commands
77 |
78 | @commands.hybrid_command(name="بن", description="بن کردن کاربر")
79 | @app_commands.describe(user="کاربری که میخواهید بن کنید")
80 | async def بن(ctx, user: discord.Member):
81 | await user.ban()
82 | await ctx.send(f"✅ {user.mention} بن شد!")
83 | ```
84 |
85 | ---
86 |
87 | ### **۶.۴ مدیریت خطا های سراسری**
88 | #### **خطا های عمومی در Cog**:
89 | ```python
90 | class Moderate(commands.Cog):
91 | #...
92 |
93 | @commands.Cog.listener()
94 | async def on_command_error(self, ctx, error):
95 | if isinstance(error, commands.CommandNotFound):
96 | await ctx.send("❌ دستور نامعتبر است!")
97 | ```
98 |
99 | ---
100 |
101 | ### **۶.۵ ساخت Help Command سفارشی**
102 |
103 | ```python
104 | class Help(commands.Cog):
105 | def __init__(self, bot):
106 | self.bot = bot
107 |
108 | @commands.hybrid_command(name="کمک")
109 | async def کمک(self, ctx):
110 | embed = discord.Embed(title="📚 راهنما")
111 | for cog in self.bot.cogs:
112 | commands_list = [f"`{cmd.name}`" for cmd in self.bot.get_cog(cog).get_commands()]
113 | embed.add_field(name=cog, value=" ".join(commands_list), inline=False)
114 | await ctx.send(embed=embed)
115 | ```
116 |
117 | ---
118 |
119 | ### **۶.۶ تمرین عملی**
120 | ۱. Cog جدیدی به نام `Fun` بسازید و دستوراتی مثل `سکه` و `شماره` را به آن منتقل کنید.
121 | ۲. دستور `!بن` را به یک Slash Command تبدیل کنید.
122 | ۳. سیستمی بسازید که کاربران فقط ۳ بار در ساعت از دستور `جوایز` استفاده کنند.
123 |
124 | ---
125 |
126 | ### **مشکلات رایج**
127 | - **Cog لود نمی شود**:
128 | - مطمئن شوید مسیر فایل (`cogs/moderate.py`) صحیح است.
129 | - از `await bot.load_extension()` استفاده کنید.
130 | - **دستورات نمایش داده نمی شوند**:
131 | - دکوراتور `@commands.command()` را فراموش نکنید.
132 |
133 | ---
134 |
135 | ### **نکات طلایی**
136 | - هر Cog را در یک فایل جداگانه ذخیره کنید.
137 | - برای نامگذاری دستورات از **فارسی** یا **انگلیسی یکدست** استفاده کنید.
138 | - از `@commands.check()` برای اعتبارسنجی های پیچیده استفاده کنید.
139 |
140 | ---
141 |
142 | **فصل بعدی**: دستورات اسلاشی (Slash Commands) و تعاملات مدرن! ✨
--------------------------------------------------------------------------------
/python/per/saeson7.md:
--------------------------------------------------------------------------------
1 | **فصل ۷: دستورات اسلشی (Slash Commands)**
2 |
3 | ---
4 |
5 | ### **۷.۱ معرفی Slash Commands**
6 | دستورات اسلشی (با پیشوند `/`) یک روش مدرن و کاربرپسند برای تعامل کاربران با ربات های دیسکورد هستند.
7 | - **مزایا**:
8 | - بدون نیاز به پیشوند (! یا ?).
9 | - رابط کاربری جذاب با پیشنهاد خودکار (Auto-Complete).
10 | - پشتیبانی از پارامتر های ساختار یافته (متن، عدد، کاربر، کانال و...).
11 |
12 | ---
13 |
14 | ### **۷.۲ تنظیمات اولیه**
15 | #### **فعال سازی Slash Commands**:
16 | ۱. در پنل توسعه دهندگان دیسکورد، **Privileged Gateway Intents** را فعال کنید:
17 | - **Server Members Intent**
18 | - **Message Content Intent**
19 |
20 | ۲. در کد، از `discord.app_commands` استفاده کنید:
21 | ```python
22 | from discord import app_commands
23 | ```
24 |
25 | ---
26 |
27 | ### **۷.۳ ساخت اولین Slash Command**
28 | #### **دستور `/پینگ`**:
29 |
30 | ```python
31 | @bot.tree.command(name="پینگ", description="بررسی پینگ ربات")
32 | async def ping(interaction: discord.Interaction):
33 | latency = round(bot.latency * 1000)
34 | await interaction.response.send_message(f"🏓 پونگ! تاخیر: {latency}ms")
35 | ```
36 |
37 | ---
38 |
39 | ### **۷.۴ ثبت و هم گامسازی دستورات**
40 | دستورات اسلشی باید با سرور های دیسکورد **همگام (Sync)** شوند تا نمایش داده شوند.
41 |
42 | #### **۱. همگام سازی دستورات در یک سرور خاص**:
43 |
44 | ```python
45 | @bot.command()
46 | @commands.is_owner()
47 | async def سینک(interaction: discord.Interaction):
48 | await bot.tree.sync(guild=discord.Object(id=GUILD_ID)) # جایگزین GUILD_ID با آیدی سرور
49 | await interaction.response.send_message("✅ دستورات همگام شدند!")
50 | ```
51 |
52 | #### **۲. همگام سازی جهانی (تمام سرور ها)**:
53 |
54 | ```python
55 | @bot.command()
56 | @commands.is_owner()
57 | async def سینک_گلوبال(interaction: discord.Interaction):
58 | await bot.tree.sync()
59 | await interaction.response.send_message("✅ دستورات جهانی همگام شدند!")
60 | ```
61 |
62 | ---
63 |
64 | ### **۷.۵ پارامتر های پیشرفته**
65 | #### **۱. دریافت ورودی از کاربر**:
66 |
67 | ```python
68 | @bot.tree.command(name="جمع", description="جمع دو عدد")
69 | @app_commands.describe(عدد1="عدد اول", عدد2="عدد دوم")
70 | async def جمع(interaction: discord.Interaction, عدد1: int, عدد2: int):
71 | await interaction.response.send_message(f"نتیجه: {عدد1 + عدد2}")
72 | ```
73 |
74 | #### **۲. پیشنهاد خودکار (Auto-Complete)**:
75 |
76 | ```python
77 | @bot.tree.command(name="رنگ", description="انتخاب رنگ")
78 | @app_commands.describe(رنگ="انتخاب کنید")
79 | @app_commands.autocomplete(رنگ=autocomplete_رنگ)
80 | async def رنگ(interaction: discord.Interaction, رنگ: str):
81 | await interaction.response.send_message(f"رنگ انتخابی: {رنگ}")
82 |
83 | # تابع Auto-Complete
84 | async def autocomplete_رنگ(
85 | interaction: discord.Interaction,
86 | current: str
87 | ) -> list[app_commands.Choice[str]]:
88 | colors = ["قرمز", "آبی", "سبز", "زرد"]
89 | return [
90 | app_commands.Choice(name=color, value=color)
91 | for color in colors if current.lower() in color.lower()
92 | ]
93 | ```
94 |
95 | ---
96 |
97 | ### **۷.۶ دستورات ترکیبی (Hybrid Commands)**
98 | دستوراتی که هم به صورت اسلشی و هم با پیشوند (!) کار می کنند:
99 |
100 | ```python
101 | from discord.ext import commands
102 |
103 | @commands.hybrid_command(name="بن", description="بن کردن کاربر")
104 | @app_commands.describe(کاربر="کاربر مورد نظر")
105 | @commands.has_permissions(ban_members=True)
106 | async def بن(ctx: commands.Context, کاربر: discord.Member):
107 | await کاربر.ban()
108 | await ctx.send(f"✅ {کاربر.mention} بن شد!")
109 | ```
110 |
111 | ---
112 |
113 | ### **۷.۷ مدیریت خطا ها**
114 | #### **خطای Missing Permissions**:
115 | ```python
116 | @بن.error
117 | async def بن_خطا(ctx: commands.Context, error):
118 | if isinstance(error, commands.MissingPermissions):
119 | await ctx.send("⛔ شما دسترسی بن کردن ندارید!")
120 | ```
121 |
122 | ---
123 |
124 | ### **تمرین عملی فصل ۷**
125 | ۱. دستور `/ساعت` بسازید که زمان فعلی را نمایش دهد.
126 | ۲. دستوری ایجاد کنید که با `/سوال [متن]` یک نظرسنجی با Reactions ایجاد کند.
127 | ۳. دستوری با Auto-Complete برای انتخاب شهر (مثلاً تهران، اصفهان، شیراز) طراحی کنید.
128 |
129 | ---
130 |
131 | ### **مشکلات رایج**
132 | - **دستورات اسلشی نمایش داده نمی شوند**:
133 | - از `await bot.tree.sync()` استفاده کنید.
134 | - ۲۴ ساعت منتظر بمانید (برای دستورات گلوبال).
135 | - **ربات به دستورات پاسخ نمی دهد**:
136 | - مطمئن شوید `@bot.event` با `on_ready` دارید.
137 | - Intent ها را در پنل توسعه دهندگان فعال کنید.
138 |
139 | ---
140 |
141 | ### **نکات کلیدی**
142 | - برای سرعت بیشتر، دستورات را ابتدا در یک سرور تستی سینک کنید.
143 | - از `interaction.response.send_message` به جای `channel.send` استفاده کنید.
144 | - برای پارامتر ها از انواع داده مثل `discord.Member` یا `int` استفاده کنید.
145 |
146 | ---
147 |
148 | **فصل بعدی**: کار با دیتابیس و ذخیره اطلاعات کاربران! 🗄️
--------------------------------------------------------------------------------
/python/per/saeson8.md:
--------------------------------------------------------------------------------
1 | **فصل ۸: کار با دیتابیس**
2 |
3 | ---
4 |
5 | ### **۸.۱ چرا به دیتابیس نیاز داریم؟**
6 | ربات های دیسکورد برای ذخیره داده های پایدار (مثل XP کاربران، تنظیمات سرور، لاگ ها و ...) نیاز به دیتابیس دارند.
7 | - **دیتابیس های رایج**:
8 | - **SQLite**: ساده، بدون نیاز به سرور، مناسب پروژه های کوچک.
9 | - **PostgreSQL/MySQL**: قدرتمند، مناسب برنامه های بزرگ.
10 | - **MongoDB**: انعطاف پذیر، مبتنی بر سند (NoSQL).
11 |
12 | ---
13 |
14 | ### **۸.۲ استفاده از SQLite (ساده ترین گزینه)**
15 | #### **۱. نصب کتابخانه `aiosqlite` (برای کار Async)**:
16 | ```bash
17 | pip install aiosqlite
18 | ```
19 |
20 | #### **۲. ایجاد اتصال به دیتابیس**:
21 | ```python
22 | import aiosqlite
23 |
24 | async def create_db():
25 | async with aiosqlite.connect("database.db") as db:
26 | await db.execute("""
27 | CREATE TABLE IF NOT EXISTS users (
28 | user_id INTEGER PRIMARY KEY,
29 | xp INTEGER DEFAULT 0,
30 | level INTEGER DEFAULT 1
31 | )
32 | """)
33 | await db.commit()
34 | ```
35 |
36 | #### **۳. افزودن داده**:
37 | ```python
38 | async def add_user(user_id: int):
39 | async with aiosqlite.connect("database.db") as db:
40 | await db.execute("INSERT OR IGNORE INTO users (user_id) VALUES (?)", (user_id,))
41 | await db.commit()
42 | ```
43 |
44 | #### **۴. خواندن داده**:
45 | ```python
46 | async def get_user(user_id: int):
47 | async with aiosqlite.connect("database.db") as db:
48 | cursor = await db.execute("SELECT * FROM users WHERE user_id = ?", (user_id,))
49 | result = await cursor.fetchone()
50 | return result # (user_id, xp, level)
51 | ```
52 |
53 | ---
54 |
55 | ### **۸.۳ سیستم XP با SQLite**
56 | #### **افزایش XP کاربر هنگام ارسال پیام**:
57 |
58 | ```python
59 | @bot.event
60 | async def on_message(message):
61 | if message.author.bot:
62 | return
63 |
64 | user_id = message.author.id
65 | await add_user(user_id) # اطمینان از وجود کاربر در دیتابیس
66 |
67 | async with aiosqlite.connect("database.db") as db:
68 | await db.execute("UPDATE users SET xp = xp + ? WHERE user_id = ?", (10, user_id))
69 | await db.commit()
70 | ```
71 |
72 | #### **دستور !سطح**:
73 |
74 | ```python
75 | @bot.command()
76 | async def سطح(ctx):
77 | user_data = await get_user(ctx.author.id)
78 | if not user_data:
79 | return await ctx.send("خطا: کاربر یافت نشد!")
80 |
81 | embed = discord.Embed(title=f"سطح {ctx.author.name}", color=0x00FF00)
82 | embed.add_field(name="XP", value=user_data[1])
83 | embed.add_field(name="سطح", value=user_data[2])
84 | await ctx.send(embed=embed)
85 | ```
86 |
87 | ---
88 |
89 | ### **۸.۴ استفاده از PostgreSQL (پیشرفته)**
90 | #### **۱. نصب `asyncpg`**:
91 | ```bash
92 | pip install asyncpg
93 | ```
94 |
95 | #### **۲. اتصال به PostgreSQL**:
96 | ```python
97 | import asyncpg
98 |
99 | async def create_pool():
100 | return await asyncpg.create_pool(
101 | user="postgres",
102 | password="password",
103 | database="mydb",
104 | host="localhost"
105 | )
106 | ```
107 |
108 | #### **۳. اجرای کوئری**:
109 | ```python
110 | pool = await create_pool()
111 |
112 | async def get_user(user_id: int):
113 | async with pool.acquire() as conn:
114 | return await conn.fetchrow("SELECT * FROM users WHERE user_id = $1", user_id)
115 | ```
116 |
117 | ---
118 |
119 | ### **۸.۵ ذخیره داده در JSON (برای پروژه های کوچک)**
120 | #### **۱. ذخیره داده**:
121 | ```python
122 | import json
123 |
124 | def save_data(data):
125 | with open("data.json", "w", encoding="utf-8") as f:
126 | json.dump(data, f, ensure_ascii=False)
127 |
128 | def load_data():
129 | try:
130 | with open("data.json", "r", encoding="utf-8") as f:
131 | return json.load(f)
132 | except FileNotFoundError:
133 | return {}
134 | ```
135 |
136 | #### **۲. مثال استفاده**:
137 | ```python
138 | data = load_data()
139 | data[str(user_id)] = {"xp": 100, "level": 2}
140 | save_data(data)
141 | ```
142 |
143 | ---
144 |
145 | ### **۸.۶ امنیت دیتابیس**
146 | - **پارامتر های امن**:
147 | همیشه از پارامترها در کوئری ها استفاده کنید تا از **تزریق SQL** جلوگیری شود.
148 | ```python
149 | # ❌ خطرناک
150 | await db.execute(f"SELECT * FROM users WHERE user_id = {user_id}")
151 |
152 | # ✅ ایمن
153 | await db.execute("SELECT * FROM users WHERE user_id = ?", (user_id,))
154 | ```
155 |
156 | - **استفاده از `.env`**:
157 | اطلاعات حساس (مثل رمز دیتابیس) را در فایل `.env` ذخیره کنید.
158 | ```env
159 | DB_PASSWORD = "your_password"
160 | ```
161 |
162 | ---
163 |
164 | ### **تمرین عملی فصل ۸**
165 | ۱. سیستمی بسازید که با هر پیام کاربر، ۵ XP اضافه کند و پس از رسیدن به ۱۰۰ XP، سطح کاربر افزایش یابد.
166 | ۲. دستور `!لیدربورد` ایجاد کنید که ۱۰ کاربر برتر را نمایش دهد.
167 | ۳. داده های تنظیمات سرور (مثل پیشوند دستورات) را در دیتابیس ذخیره کنید.
168 |
169 | ---
170 |
171 | ### **مشکلات رایج**
172 | - **خطای اتصال به دیتابیس**:
173 | - مطمئن شوید دیتابیس در حال اجراست (مثلاً PostgreSQL).
174 | - اطلاعات اتصال (مثل رمز عبور) را بررسی کنید.
175 | - **داده ها ذخیره نمی شوند**:
176 | - فراموش نکنید بعد از کوئری های تغییردهنده (`INSERT`, `UPDATE`) از `commit()` استفاده کنید.
177 |
178 | ---
179 |
180 | ### **نکات کلیدی**
181 | - برای پروژه های بزرگ، از **ORM**هایی مثل `SQLAlchemy` استفاده کنید.
182 | - برای عملکرد بهتر در ربات های بزرگ، از **Connection Pooling** استفاده کنید.
183 | - همیشه قبل از اجرای ربات، ساختار دیتابیس را بررسی کنید (مثلاً با اسکریپت های `CREATE TABLE`).
184 |
185 | ---
186 |
187 | **فصل بعدی**: مدیریت سرور و کاربران! ⚙
--------------------------------------------------------------------------------
/python/per/saeson9.md:
--------------------------------------------------------------------------------
1 | **فصل ۹: مدیریت سرور و کاربران**
2 |
3 | ---
4 |
5 | ### **۹.۱ دسترسی های مورد نیاز (Permissions)**
6 | برای مدیریت سرور و کاربران، ربات باید **دسترسی های لازم** را داشته باشد. این دسترسی ها را میتوان در کد یا پنل توسعه دهندگان دیسکورد تنظیم کرد.
7 |
8 | #### **فعال سازی اینتنت ها**:
9 | - **Server Members Intent**: برای دسترسی به لیست اعضا.
10 | - **Moderate Members**: برای میوت یا بن کردن کاربران.
11 |
12 | #### **تعیین دسترسی ها در کد**:
13 |
14 | ```python
15 | intents = discord.Intents.default()
16 | intents.members = True # دسترسی به اعضا
17 | intents.moderation = True # دسترسی به مدیریت کاربران
18 |
19 | bot = commands.Bot(
20 | command_prefix="!",
21 | intents=intents
22 | )
23 | ```
24 |
25 | ---
26 |
27 | ### **۹.۲ دستورات مدیریت کاربران**
28 | #### **۱. بن کردن (Ban)**:
29 |
30 | ```python
31 | @bot.command()
32 | @commands.has_permissions(ban_members=True)
33 | async def بن(ctx, member: discord.Member, reason: str = "دلیل مشخص نشده"):
34 | await member.ban(reason=reason)
35 | await ctx.send(f"✅ {member.mention} با موفقیت بن شد!\nدلیل: **{reason}**")
36 |
37 | @بن.error
38 | async def بن_خطا(ctx, error):
39 | if isinstance(error, commands.MissingPermissions):
40 | await ctx.send("⛔ شما دسترسی بن کردن کاربران را ندارید!")
41 | ```
42 |
43 | #### **۲. آنبن کردن (Unban)**:
44 |
45 | ```python
46 | @bot.command()
47 | @commands.has_permissions(ban_members=True)
48 | async def آنبن(ctx, user_id: int):
49 | user = await bot.fetch_user(user_id)
50 | await ctx.guild.unban(user)
51 | await ctx.send(f"✅ {user.mention} آنبن شد!")
52 | ```
53 |
54 | #### **۳. میوت کردن (Mute)**:
55 |
56 | ```python
57 | @bot.command()
58 | @commands.has_permissions(moderate_members=True)
59 | async def میوت(ctx, member: discord.Member, minutes: int = 10):
60 | duration = datetime.timedelta(minutes=minutes)
61 | await member.timeout(duration)
62 | await ctx.send(f"⏳ {member.mention} به مدت **{minutes} دقیقه** میوت شد!")
63 | ```
64 |
65 | ---
66 |
67 | ### **۹.۳ مدیریت پیام ها**
68 | #### **۱. پاک کردن پیام ها (Purge)**:
69 |
70 | ```python
71 | @bot.command()
72 | @commands.has_permissions(manage_messages=True)
73 | async def پاککن(ctx, limit: int = 10):
74 | await ctx.channel.purge(limit=limit + 1) # +1 برای حذف دستور
75 | msg = await ctx.send(f"✅ {limit} پیام پاک شد!", delete_after=5)
76 |
77 | @پاککن.error
78 | async def پاککن_خطا(ctx, error):
79 | if isinstance(error, commands.MissingPermissions):
80 | await ctx.send("⛔ شما دسترسی مدیریت پیام ها را ندارید!")
81 | ```
82 |
83 | #### **۲. گزارش پیام (Report)**:
84 |
85 | ```python
86 | @bot.command()
87 | async def گزارش(ctx, message_id: str):
88 | message = await ctx.channel.fetch_message(int(message_id))
89 | embed = discord.Embed(
90 | title="⚠️ گزارش پیام",
91 | description=message.content,
92 | color=discord.Color.red()
93 | )
94 | embed.set_author(name=message.author.name, icon_url=message.author.avatar.url)
95 | admin_channel = bot.get_channel(ADMIN_CHANNEL_ID) # جایگزین با آیدی کانال ادمین ها
96 | await admin_channel.send(embed=embed)
97 | ```
98 |
99 | ---
100 |
101 | ### **۹.۴ مدیریت نقش ها (Roles)**
102 | #### **۱. افزودن نقش به کاربر**:
103 |
104 | ```python
105 | @bot.command()
106 | @commands.has_permissions(manage_roles=True)
107 | async def افزودن_نقش(ctx, member: discord.Member, role: discord.Role):
108 | await member.add_roles(role)
109 | await ctx.send(f"✅ نقش {role.mention} به {member.mention} داده شد!")
110 | ```
111 |
112 | #### **۲. ساخت نقش جدید**:
113 | ```python
114 | @bot.command()
115 | @commands.has_permissions(manage_roles=True)
116 | async def ساخت_نقش(ctx, name: str, color: str = "FFFFFF"):
117 | color = int(color, 16) # تبدیل کد HEX به عدد
118 | await ctx.guild.create_role(name=name, color=discord.Color(color))
119 | await ctx.send(f"✅ نقش **{name}** ساخته شد!")
120 | ```
121 |
122 | ---
123 |
124 | ### **۹.۵ سیستم تیکت (Ticket System)**
125 | #### **۱. ساخت کانال تیکت**:
126 |
127 | ```python
128 | @bot.command()
129 | @commands.has_permissions(manage_channels=True)
130 | async def تیکت(ctx, reason: str):
131 | overwrites = {
132 | ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False),
133 | ctx.author: discord.PermissionOverwrite(read_messages=True)
134 | }
135 | channel = await ctx.guild.create_text_channel(
136 | name=f"تیکت-{ctx.author.name}",
137 | overwrites=overwrites
138 | )
139 | await channel.send(f"📩 تیکت شما با دلیل **{reason}** ایجاد شد!")
140 | ```
141 |
142 | #### **۲. بستن تیکت**:
143 |
144 | ```python
145 | @bot.command()
146 | async def بستن(ctx):
147 | if "تیکت" in ctx.channel.name:
148 | await ctx.channel.delete()
149 | ```
150 |
151 | ---
152 |
153 | ### **تمرین عملی فصل ۹**
154 | ۱. دستوری بسازید که کاربران را بر اساس فعالیت (تعداد پیام ها) رتبه بندی کند.
155 | ۲. سیستمی طراحی کنید که هنگام میوت کردن کاربر، دلیل را در لاگ ذخیره کند.
156 | ۳. دستوری ایجاد کنید که با `!ایجاد_کانال [نام]` یک کانال جدید بسازد.
157 |
158 | ---
159 |
160 | ### **مشکلات رایج**
161 | - **ربات نمی تواند کاربر را بن/میوت کند**:
162 | - مطمئن شوید ربات **بالاتر از نقش کاربر** در سلسله مراتب سرور است.
163 | - دسترسی های ربات را در سرور بررسی کنید.
164 | - **خطای Missing Permissions**:
165 | - از دکوراتور `@commands.has_permissions()` استفاده کنید.
166 |
167 | ---
168 |
169 | ### **نکات امنیتی**
170 | - هرگز به ربات دسترسی **Administrator** ندهید مگر در موارد ضروری.
171 | - برای دستورات حساس، از احراز هویت دو مرحله ای (2FA) در سرور استفاده کنید.
172 | - لاگ تمام عملیات های مدیریتی را در یک کانال خصوصی ذخیره کنید.
173 |
174 | ---
175 |
176 | **فصل بعدی**: استقرار ربات (Deploy) و نگه داری حرفه ای! 🚀
--------------------------------------------------------------------------------