1 | <?php |
||
30 | trait User |
||
31 | { |
||
32 | /** @} */ |
||
33 | |||
34 | abstract function getChat($chat_id); |
||
35 | |||
36 | abstract function setChatID($chat_id); |
||
37 | |||
38 | /** PDO connection to the database. */ |
||
39 | public $pdo; |
||
40 | |||
41 | /** |
||
42 | * \addtogroup Bot Bot |
||
43 | * @{ |
||
44 | */ |
||
45 | |||
46 | /** |
||
47 | * \addtogroup Users-handle Users handling |
||
48 | * \brief Handle bot users on the database. |
||
49 | * @{ |
||
50 | */ |
||
51 | |||
52 | /** \brief Table contaning bot users data in the SQL database. */ |
||
53 | public $user_table = '"User"'; |
||
54 | |||
55 | /** \brief Name of the column that represents the user id in the sql database */ |
||
56 | public $id_column = 'chat_id'; |
||
57 | |||
58 | /** \brief Add a user to the database. |
||
59 | * \details Add a user to the database in Bot::$user_table table and Bot::$id_column column using Bot::$pdo connection. |
||
60 | * @param string|int $chat_id chat ID of the user to add. |
||
61 | * @return bool True on success. |
||
62 | */ |
||
63 | 1 | public function addUser($chat_id) : bool |
|
64 | { |
||
65 | 1 | if (!isset($this->pdo)) { |
|
66 | throw new BotException("Database connection not set"); |
||
67 | } |
||
68 | |||
69 | // Create insertion query and initialize variable |
||
70 | 1 | $query = "INSERT INTO $this->user_table ($this->id_column) VALUES (:chat_id)"; |
|
71 | |||
72 | 1 | $sth = $this->pdo->prepare($query); |
|
73 | 1 | $sth->bindParam(':chat_id', $chat_id); |
|
74 | |||
75 | try { |
||
76 | 1 | $sth->execute(); |
|
77 | 1 | $success = true; |
|
78 | } catch (\PDOException $e) { |
||
79 | echo $e->getMessage(); |
||
80 | |||
81 | $success = false; |
||
82 | } |
||
83 | |||
84 | 1 | $sth = null; |
|
85 | 1 | return $success; |
|
86 | } |
||
87 | |||
88 | /** |
||
89 | * \brief Send a message to every user available on the database. |
||
90 | * \details Send a message to all subscribed users, change Bot::$user_table and Bot::$id_column to match your database structure. |
||
91 | * This method requires Bot::$pdo connection set. |
||
92 | * All parameters are the same as CoreBot::sendMessage. |
||
93 | * Because a limitation of Telegram Bot API the bot will have a delay after 20 messages sent in different chats. |
||
94 | * @return int How many messages were sent. |
||
95 | * @see CoreBot::sendMessage |
||
96 | */ |
||
97 | 1 | public function broadcastMessage( |
|
129 | |||
130 | /** @} */ |
||
131 | |||
132 | /** @} */ |
||
133 | } |
||
134 |
Adding explicit visibility (
private
,protected
, orpublic
) is generally recommend to communicate to other developers how, and from where this method is intended to be used.