Guest User

[Pyton 3]Discord hack by FahroDab, figure out how it works.

a guest
Dec 30th, 2016
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 110.54 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. """
  4. The MIT License (MIT)
  5.  
  6. Copyright (c) 2015-2016 Rapptz
  7.  
  8. Permission is hereby granted, free of charge, to any person obtaining a
  9. copy of this software and associated documentation files (the "Software"),
  10. to deal in the Software without restriction, including without limitation
  11. the rights to use, copy, modify, merge, publish, distribute, sublicense,
  12. and/or sell copies of the Software, and to permit persons to whom the
  13. Software is furnished to do so, subject to the following conditions:
  14.  
  15. The above copyright notice and this permission notice shall be included in
  16. all copies or substantial portions of the Software.
  17.  
  18. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  19. OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  23. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  24. DEALINGS IN THE SOFTWARE.
  25. """
  26.  
  27. from . import __version__ as library_version
  28. from .user import User
  29. from .member import Member
  30. from .channel import Channel, PrivateChannel
  31. from .server import Server
  32. from .message import Message
  33. from .invite import Invite
  34. from .object import Object
  35. from .reaction import Reaction
  36. from .role import Role
  37. from .errors import *
  38. from .state import ConnectionState
  39. from .permissions import Permissions, PermissionOverwrite
  40. from . import utils, compat
  41. from .enums import ChannelType, ServerRegion, VerificationLevel, Status
  42. from .voice_client import VoiceClient
  43. from .iterators import LogsFromIterator
  44. from .gateway import *
  45. from .emoji import Emoji
  46. from .http import HTTPClient
  47.  
  48. import asyncio
  49. import aiohttp
  50. import websockets
  51.  
  52. import logging, traceback
  53. import sys, re, io, enum
  54. import tempfile, os, hashlib
  55. import itertools
  56. import datetime
  57. from collections import namedtuple
  58. from os.path import split as path_split
  59.  
  60. PY35 = sys.version_info >= (3, 5)
  61. log = logging.getLogger(__name__)
  62.  
  63. AppInfo = namedtuple('AppInfo', 'id name description icon owner')
  64. WaitedReaction = namedtuple('WaitedReaction', 'reaction user')
  65.  
  66. def app_info_icon_url(self):
  67. """Retrieves the application's icon_url if it exists. Empty string otherwise."""
  68. if not self.icon:
  69. return ''
  70.  
  71. return 'https://cdn.discordapp.com/app-icons/{0.id}/{0.icon}.jpg'.format(self)
  72.  
  73. AppInfo.icon_url = property(app_info_icon_url)
  74.  
  75. class WaitForType(enum.Enum):
  76. message = 0
  77. reaction = 1
  78.  
  79. ChannelPermissions = namedtuple('ChannelPermissions', 'target overwrite')
  80. ChannelPermissions.__new__.__defaults__ = (PermissionOverwrite(),)
  81.  
  82. class Client:
  83. """Represents a client connection that connects to Discord.
  84. This class is used to interact with the Discord WebSocket and API.
  85.  
  86. A number of options can be passed to the :class:`Client`.
  87.  
  88. .. _deque: https://docs.python.org/3.4/library/collections.html#collections.deque
  89. .. _event loop: https://docs.python.org/3/library/asyncio-eventloops.html
  90. .. _connector: http://aiohttp.readthedocs.org/en/stable/client_reference.html#connectors
  91. .. _ProxyConnector: http://aiohttp.readthedocs.org/en/stable/client_reference.html#proxyconnector
  92.  
  93. Parameters
  94. ----------
  95. max_messages : Optional[int]
  96. The maximum number of messages to store in :attr:`messages`.
  97. This defaults to 5000. Passing in `None` or a value less than 100
  98. will use the default instead of the passed in value.
  99. loop : Optional[event loop].
  100. The `event loop`_ to use for asynchronous operations. Defaults to ``None``,
  101. in which case the default event loop is used via ``asyncio.get_event_loop()``.
  102. cache_auth : Optional[bool]
  103. Indicates if :meth:`login` should cache the authentication tokens. Defaults
  104. to ``True``. The method in which the cache is written is done by writing to
  105. disk to a temporary directory.
  106. connector : aiohttp.BaseConnector
  107. The `connector`_ to use for connection pooling. Useful for proxies, e.g.
  108. with a `ProxyConnector`_.
  109. shard_id : Optional[int]
  110. Integer starting at 0 and less than shard_count.
  111. shard_count : Optional[int]
  112. The total number of shards.
  113.  
  114. Attributes
  115. -----------
  116. user : Optional[:class:`User`]
  117. Represents the connected client. None if not logged in.
  118. voice_clients : iterable of :class:`VoiceClient`
  119. Represents a list of voice connections. To connect to voice use
  120. :meth:`join_voice_channel`. To query the voice connection state use
  121. :meth:`is_voice_connected`.
  122. servers : iterable of :class:`Server`
  123. The servers that the connected client is a member of.
  124. private_channels : iterable of :class:`PrivateChannel`
  125. The private channels that the connected client is participating on.
  126. messages
  127. A deque_ of :class:`Message` that the client has received from all
  128. servers and private messages. The number of messages stored in this
  129. deque is controlled by the ``max_messages`` parameter.
  130. email
  131. The email used to login. This is only set if login is successful,
  132. otherwise it's None.
  133. ws
  134. The websocket gateway the client is currently connected to. Could be None.
  135. loop
  136. The `event loop`_ that the client uses for HTTP requests and websocket operations.
  137.  
  138. """
  139. def __init__(self, *, loop=None, **options):
  140. self.ws = None
  141. self.email = None
  142. self.loop = asyncio.get_event_loop() if loop is None else loop
  143. self._listeners = []
  144. self.cache_auth = options.get('cache_auth', True)
  145. self.shard_id = options.get('shard_id')
  146. self.shard_count = options.get('shard_count')
  147.  
  148. max_messages = options.get('max_messages')
  149. if max_messages is None or max_messages < 100:
  150. max_messages = 5000
  151.  
  152. self.connection = ConnectionState(self.dispatch, self.request_offline_members,
  153. self._syncer, max_messages, loop=self.loop)
  154.  
  155. connector = options.pop('connector', None)
  156. self.http = HTTPClient(connector, loop=self.loop)
  157.  
  158. self._closed = asyncio.Event(loop=self.loop)
  159. self._is_logged_in = asyncio.Event(loop=self.loop)
  160. self._is_ready = asyncio.Event(loop=self.loop)
  161.  
  162. if VoiceClient.warn_nacl:
  163. VoiceClient.warn_nacl = False
  164. log.warning("PyNaCl is not installed, voice will NOT be supported")
  165.  
  166. # internals
  167.  
  168. @asyncio.coroutine
  169. def _syncer(self, guilds):
  170. yield from self.ws.request_sync(guilds)
  171.  
  172. def _get_cache_filename(self, email):
  173. filename = hashlib.md5(email.encode('utf-8')).hexdigest()
  174. return os.path.join(tempfile.gettempdir(), 'discord_py', filename)
  175.  
  176. def _get_cache_token(self, email, password):
  177. try:
  178. log.info('attempting to login via cache')
  179. cache_file = self._get_cache_filename(email)
  180. self.email = email
  181. with open(cache_file, 'r') as f:
  182. log.info('login cache file found')
  183. return f.read()
  184.  
  185. # at this point our check failed
  186. # so we have to login and get the proper token and then
  187. # redo the cache
  188. except OSError:
  189. log.info('a problem occurred while opening login cache')
  190. return None # file not found et al
  191.  
  192. def _update_cache(self, email, password):
  193. try:
  194. cache_file = self._get_cache_filename(email)
  195. os.makedirs(os.path.dirname(cache_file), exist_ok=True)
  196. with os.fdopen(os.open(cache_file, os.O_WRONLY | os.O_CREAT, 0o0600), 'w') as f:
  197. log.info('updating login cache')
  198. f.write(self.http.token)
  199. except OSError:
  200. log.info('a problem occurred while updating the login cache')
  201. pass
  202.  
  203. def handle_reaction_add(self, reaction, user):
  204. removed = []
  205. for i, (condition, future, event_type) in enumerate(self._listeners):
  206. if event_type is not WaitForType.reaction:
  207. continue
  208.  
  209. if future.cancelled():
  210. removed.append(i)
  211. continue
  212.  
  213. try:
  214. result = condition(reaction, user)
  215. except Exception as e:
  216. future.set_exception(e)
  217. removed.append(i)
  218. else:
  219. if result:
  220. future.set_result(WaitedReaction(reaction, user))
  221. removed.append(i)
  222.  
  223.  
  224. for idx in reversed(removed):
  225. del self._listeners[idx]
  226.  
  227. def handle_message(self, message):
  228. removed = []
  229. for i, (condition, future, event_type) in enumerate(self._listeners):
  230. if event_type is not WaitForType.message:
  231. continue
  232.  
  233. if future.cancelled():
  234. removed.append(i)
  235. continue
  236.  
  237. try:
  238. result = condition(message)
  239. except Exception as e:
  240. future.set_exception(e)
  241. removed.append(i)
  242. else:
  243. if result:
  244. future.set_result(message)
  245. removed.append(i)
  246.  
  247.  
  248. for idx in reversed(removed):
  249. del self._listeners[idx]
  250.  
  251. def handle_ready(self):
  252. self._is_ready.set()
  253.  
  254. def _resolve_invite(self, invite):
  255. if isinstance(invite, Invite) or isinstance(invite, Object):
  256. return invite.id
  257. else:
  258. rx = r'(?:https?\:\/\/)?discord\.gg\/(.+)'
  259. m = re.match(rx, invite)
  260. if m:
  261. return m.group(1)
  262. return invite
  263.  
  264. @asyncio.coroutine
  265. def _resolve_destination(self, destination):
  266. if isinstance(destination, Channel):
  267. return destination.id, destination.server.id
  268. elif isinstance(destination, PrivateChannel):
  269. return destination.id, None
  270. elif isinstance(destination, Server):
  271. return destination.id, destination.id
  272. elif isinstance(destination, User):
  273. found = self.connection._get_private_channel_by_user(destination.id)
  274. if found is None:
  275. # Couldn't find the user, so start a PM with them first.
  276. channel = yield from self.start_private_message(destination)
  277. return channel.id, None
  278. else:
  279. return found.id, None
  280. elif isinstance(destination, Object):
  281. found = self.get_channel(destination.id)
  282. if found is not None:
  283. return (yield from self._resolve_destination(found))
  284.  
  285. # couldn't find it in cache so YOLO
  286. return destination.id, destination.id
  287. else:
  288. fmt = 'Destination must be Channel, PrivateChannel, User, or Object. Received {0.__class__.__name__}'
  289. raise InvalidArgument(fmt.format(destination))
  290.  
  291. def __getattr__(self, name):
  292. if name in ('user', 'servers', 'private_channels', 'messages', 'voice_clients'):
  293. return getattr(self.connection, name)
  294. else:
  295. msg = "'{}' object has no attribute '{}'"
  296. raise AttributeError(msg.format(self.__class__, name))
  297.  
  298. def __setattr__(self, name, value):
  299. if name in ('user', 'servers', 'private_channels', 'messages', 'voice_clients'):
  300. return setattr(self.connection, name, value)
  301. else:
  302. object.__setattr__(self, name, value)
  303.  
  304. @asyncio.coroutine
  305. def _run_event(self, event, *args, **kwargs):
  306. try:
  307. yield from getattr(self, event)(*args, **kwargs)
  308. except asyncio.CancelledError:
  309. pass
  310. except Exception:
  311. try:
  312. yield from self.on_error(event, *args, **kwargs)
  313. except asyncio.CancelledError:
  314. pass
  315.  
  316. def dispatch(self, event, *args, **kwargs):
  317. log.debug('Dispatching event {}'.format(event))
  318. method = 'on_' + event
  319. handler = 'handle_' + event
  320.  
  321. if hasattr(self, handler):
  322. getattr(self, handler)(*args, **kwargs)
  323.  
  324. if hasattr(self, method):
  325. compat.create_task(self._run_event(method, *args, **kwargs), loop=self.loop)
  326.  
  327. @asyncio.coroutine
  328. def on_error(self, event_method, *args, **kwargs):
  329. """|coro|
  330.  
  331. The default error handler provided by the client.
  332.  
  333. By default this prints to ``sys.stderr`` however it could be
  334. overridden to have a different implementation.
  335. Check :func:`discord.on_error` for more details.
  336. """
  337. print('Ignoring exception in {}'.format(event_method), file=sys.stderr)
  338. traceback.print_exc()
  339.  
  340. # login state management
  341.  
  342. @asyncio.coroutine
  343. def _login_1(self, token, **kwargs):
  344. log.info('logging in using static token')
  345. is_bot = kwargs.pop('bot', True)
  346. data = yield from self.http.static_login(token, bot=is_bot)
  347. self.email = data.get('email', None)
  348. self.connection.is_bot = is_bot
  349. self._is_logged_in.set()
  350.  
  351. @asyncio.coroutine
  352. def _login_2(self, email, password, **kwargs):
  353. # attempt to read the token from cache
  354. self.connection.is_bot = False
  355.  
  356. if self.cache_auth:
  357. token = self._get_cache_token(email, password)
  358. try:
  359. yield from self.http.static_login(token, bot=False)
  360. except:
  361. log.info('cache auth token is out of date')
  362. else:
  363. self._is_logged_in.set()
  364. return
  365.  
  366.  
  367. yield from self.http.email_login(email, password)
  368. self.email = email
  369. self._is_logged_in.set()
  370.  
  371. # since we went through all this trouble
  372. # let's make sure we don't have to do it again
  373. if self.cache_auth:
  374. self._update_cache(email, password)
  375.  
  376. @asyncio.coroutine
  377. def login(self, *args, **kwargs):
  378. """|coro|
  379.  
  380. Logs in the client with the specified credentials.
  381.  
  382. This function can be used in two different ways.
  383.  
  384. .. code-block:: python
  385.  
  386. await client.login('token')
  387.  
  388. # or
  389.  
  390. await client.login('email', 'password')
  391.  
  392. More than 2 parameters or less than 1 parameter raises a
  393. :exc:`TypeError`.
  394.  
  395. Parameters
  396. -----------
  397. bot : bool
  398. Keyword argument that specifies if the account logging on is a bot
  399. token or not. Only useful for logging in with a static token.
  400. Ignored for the email and password combo. Defaults to ``True``.
  401.  
  402. Raises
  403. ------
  404. LoginFailure
  405. The wrong credentials are passed.
  406. HTTPException
  407. An unknown HTTP related error occurred,
  408. usually when it isn't 200 or the known incorrect credentials
  409. passing status code.
  410. TypeError
  411. The incorrect number of parameters is passed.
  412. """
  413.  
  414. n = len(args)
  415. if n in (2, 1):
  416. yield from getattr(self, '_login_' + str(n))(*args, **kwargs)
  417. else:
  418. raise TypeError('login() takes 1 or 2 positional arguments but {} were given'.format(n))
  419.  
  420. @asyncio.coroutine
  421. def logout(self):
  422. """|coro|
  423.  
  424. Logs out of Discord and closes all connections.
  425. """
  426. yield from self.close()
  427. self._is_logged_in.clear()
  428.  
  429. @asyncio.coroutine
  430. def connect(self):
  431. """|coro|
  432.  
  433. Creates a websocket connection and lets the websocket listen
  434. to messages from discord.
  435.  
  436. Raises
  437. -------
  438. GatewayNotFound
  439. If the gateway to connect to discord is not found. Usually if this
  440. is thrown then there is a discord API outage.
  441. ConnectionClosed
  442. The websocket connection has been terminated.
  443. """
  444. self.ws = yield from DiscordWebSocket.from_client(self)
  445.  
  446. while not self.is_closed:
  447. try:
  448. yield from self.ws.poll_event()
  449. except (ReconnectWebSocket, ResumeWebSocket) as e:
  450. resume = type(e) is ResumeWebSocket
  451. log.info('Got ' + type(e).__name__)
  452. self.ws = yield from DiscordWebSocket.from_client(self, resume=resume)
  453. except ConnectionClosed as e:
  454. yield from self.close()
  455. if e.code != 1000:
  456. raise
  457.  
  458. @asyncio.coroutine
  459. def close(self):
  460. """|coro|
  461.  
  462. Closes the connection to discord.
  463. """
  464. if self.is_closed:
  465. return
  466.  
  467. for voice in list(self.voice_clients):
  468. try:
  469. yield from voice.disconnect()
  470. except:
  471. # if an error happens during disconnects, disregard it.
  472. pass
  473.  
  474. self.connection._remove_voice_client(voice.server.id)
  475.  
  476. if self.ws is not None and self.ws.open:
  477. yield from self.ws.close()
  478.  
  479.  
  480. yield from self.http.close()
  481. self._closed.set()
  482. self._is_ready.clear()
  483.  
  484. @asyncio.coroutine
  485. def start(self, *args, **kwargs):
  486. """|coro|
  487.  
  488. A shorthand coroutine for :meth:`login` + :meth:`connect`.
  489. """
  490. yield from self.login(*args, **kwargs)
  491. yield from self.connect()
  492.  
  493. def run(self, *args, **kwargs):
  494. """A blocking call that abstracts away the `event loop`_
  495. initialisation from you.
  496.  
  497. If you want more control over the event loop then this
  498. function should not be used. Use :meth:`start` coroutine
  499. or :meth:`connect` + :meth:`login`.
  500.  
  501. Roughly Equivalent to: ::
  502.  
  503. try:
  504. loop.run_until_complete(start(*args, **kwargs))
  505. except KeyboardInterrupt:
  506. loop.run_until_complete(logout())
  507. # cancel all tasks lingering
  508. finally:
  509. loop.close()
  510.  
  511. Warning
  512. --------
  513. This function must be the last function to call due to the fact that it
  514. is blocking. That means that registration of events or anything being
  515. called after this function call will not execute until it returns.
  516. """
  517.  
  518. try:
  519. self.loop.run_until_complete(self.start(*args, **kwargs))
  520. except KeyboardInterrupt:
  521. self.loop.run_until_complete(self.logout())
  522. pending = asyncio.Task.all_tasks(loop=self.loop)
  523. gathered = asyncio.gather(*pending, loop=self.loop)
  524. try:
  525. gathered.cancel()
  526. self.loop.run_until_complete(gathered)
  527.  
  528. # we want to retrieve any exceptions to make sure that
  529. # they don't nag us about it being un-retrieved.
  530. gathered.exception()
  531. except:
  532. pass
  533. finally:
  534. self.loop.close()
  535.  
  536. # properties
  537.  
  538. @property
  539. def is_logged_in(self):
  540. """bool: Indicates if the client has logged in successfully."""
  541. return self._is_logged_in.is_set()
  542.  
  543. @property
  544. def is_closed(self):
  545. """bool: Indicates if the websocket connection is closed."""
  546. return self._closed.is_set()
  547.  
  548. # helpers/getters
  549.  
  550. def get_channel(self, id):
  551. """Returns a :class:`Channel` or :class:`PrivateChannel` with the following ID. If not found, returns None."""
  552. return self.connection.get_channel(id)
  553.  
  554. def get_server(self, id):
  555. """Returns a :class:`Server` with the given ID. If not found, returns None."""
  556. return self.connection._get_server(id)
  557.  
  558. def get_all_emojis(self):
  559. """Returns a generator with every :class:`Emoji` the client can see."""
  560. for server in self.servers:
  561. for emoji in server.emojis:
  562. yield emoji
  563.  
  564. def get_all_channels(self):
  565. """A generator that retrieves every :class:`Channel` the client can 'access'.
  566.  
  567. This is equivalent to: ::
  568.  
  569. for server in client.servers:
  570. for channel in server.channels:
  571. yield channel
  572.  
  573. Note
  574. -----
  575. Just because you receive a :class:`Channel` does not mean that
  576. you can communicate in said channel. :meth:`Channel.permissions_for` should
  577. be used for that.
  578. """
  579.  
  580. for server in self.servers:
  581. for channel in server.channels:
  582. yield channel
  583.  
  584. def get_all_members(self):
  585. """Returns a generator with every :class:`Member` the client can see.
  586.  
  587. This is equivalent to: ::
  588.  
  589. for server in client.servers:
  590. for member in server.members:
  591. yield member
  592.  
  593. """
  594. for server in self.servers:
  595. for member in server.members:
  596. yield member
  597.  
  598. # listeners/waiters
  599.  
  600. @asyncio.coroutine
  601. def wait_until_ready(self):
  602. """|coro|
  603.  
  604. This coroutine waits until the client is all ready. This could be considered
  605. another way of asking for :func:`discord.on_ready` except meant for your own
  606. background tasks.
  607. """
  608. yield from self._is_ready.wait()
  609.  
  610. @asyncio.coroutine
  611. def wait_until_login(self):
  612. """|coro|
  613.  
  614. This coroutine waits until the client is logged on successfully. This
  615. is different from waiting until the client's state is all ready. For
  616. that check :func:`discord.on_ready` and :meth:`wait_until_ready`.
  617. """
  618. yield from self._is_logged_in.wait()
  619.  
  620. @asyncio.coroutine
  621. def wait_for_message(self, timeout=None, *, author=None, channel=None, content=None, check=None):
  622. """|coro|
  623.  
  624. Waits for a message reply from Discord. This could be seen as another
  625. :func:`discord.on_message` event outside of the actual event. This could
  626. also be used for follow-ups and easier user interactions.
  627.  
  628. The keyword arguments passed into this function are combined using the logical and
  629. operator. The ``check`` keyword argument can be used to pass in more complicated
  630. checks and must be a regular function (not a coroutine).
  631.  
  632. The ``timeout`` parameter is passed into `asyncio.wait_for`_. By default, it
  633. does not timeout. Instead of throwing ``asyncio.TimeoutError`` the coroutine
  634. catches the exception and returns ``None`` instead of a :class:`Message`.
  635.  
  636. If the ``check`` predicate throws an exception, then the exception is propagated.
  637.  
  638. This function returns the **first message that meets the requirements**.
  639.  
  640. .. _asyncio.wait_for: https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for
  641.  
  642. Examples
  643. ----------
  644.  
  645. Basic example:
  646.  
  647. .. code-block:: python
  648. :emphasize-lines: 5
  649.  
  650. @client.event
  651. async def on_message(message):
  652. if message.content.startswith('$greet'):
  653. await client.send_message(message.channel, 'Say hello')
  654. msg = await client.wait_for_message(author=message.author, content='hello')
  655. await client.send_message(message.channel, 'Hello.')
  656.  
  657. Asking for a follow-up question:
  658.  
  659. .. code-block:: python
  660. :emphasize-lines: 6
  661.  
  662. @client.event
  663. async def on_message(message):
  664. if message.content.startswith('$start'):
  665. await client.send_message(message.channel, 'Type $stop 4 times.')
  666. for i in range(4):
  667. msg = await client.wait_for_message(author=message.author, content='$stop')
  668. fmt = '{} left to go...'
  669. await client.send_message(message.channel, fmt.format(3 - i))
  670.  
  671. await client.send_message(message.channel, 'Good job!')
  672.  
  673. Advanced filters using ``check``:
  674.  
  675. .. code-block:: python
  676. :emphasize-lines: 9
  677.  
  678. @client.event
  679. async def on_message(message):
  680. if message.content.startswith('$cool'):
  681. await client.send_message(message.channel, 'Who is cool? Type $name namehere')
  682.  
  683. def check(msg):
  684. return msg.content.startswith('$name')
  685.  
  686. message = await client.wait_for_message(author=message.author, check=check)
  687. name = message.content[len('$name'):].strip()
  688. await client.send_message(message.channel, '{} is cool indeed'.format(name))
  689.  
  690.  
  691. Parameters
  692. -----------
  693. timeout : float
  694. The number of seconds to wait before returning ``None``.
  695. author : :class:`Member` or :class:`User`
  696. The author the message must be from.
  697. channel : :class:`Channel` or :class:`PrivateChannel` or :class:`Object`
  698. The channel the message must be from.
  699. content : str
  700. The exact content the message must have.
  701. check : function
  702. A predicate for other complicated checks. The predicate must take
  703. a :class:`Message` as its only parameter.
  704.  
  705. Returns
  706. --------
  707. :class:`Message`
  708. The message that you requested for.
  709. """
  710.  
  711. def predicate(message):
  712. result = True
  713. if author is not None:
  714. result = result and message.author == author
  715.  
  716. if content is not None:
  717. result = result and message.content == content
  718.  
  719. if channel is not None:
  720. result = result and message.channel.id == channel.id
  721.  
  722. if callable(check):
  723. # the exception thrown by check is propagated through the future.
  724. result = result and check(message)
  725.  
  726. return result
  727.  
  728. future = asyncio.Future(loop=self.loop)
  729. self._listeners.append((predicate, future, WaitForType.message))
  730. try:
  731. message = yield from asyncio.wait_for(future, timeout, loop=self.loop)
  732. except asyncio.TimeoutError:
  733. message = None
  734. return message
  735.  
  736.  
  737. @asyncio.coroutine
  738. def wait_for_reaction(self, emoji=None, *, user=None, timeout=None, message=None, check=None):
  739. """|coro|
  740.  
  741. Waits for a message reaction from Discord. This is similar to :meth:`wait_for_message`
  742. and could be seen as another :func:`on_reaction_add` event outside of the actual event.
  743. This could be used for follow up situations.
  744.  
  745. Similar to :meth:`wait_for_message`, the keyword arguments are combined using logical
  746. AND operator. The ``check`` keyword argument can be used to pass in more complicated
  747. checks and must a regular function taking in two arguments, ``(reaction, user)``. It
  748. must not be a coroutine.
  749.  
  750. The ``timeout`` parameter is passed into asyncio.wait_for. By default, it
  751. does not timeout. Instead of throwing ``asyncio.TimeoutError`` the coroutine
  752. catches the exception and returns ``None`` instead of a the ``(reaction, user)``
  753. tuple.
  754.  
  755. If the ``check`` predicate throws an exception, then the exception is propagated.
  756.  
  757. The ``emoji`` parameter can be either a :class:`Emoji`, a ``str`` representing
  758. an emoji, or a sequence of either type. If the ``emoji`` parameter is a sequence
  759. then the first reaction emoji that is in the list is returned. If ``None`` is
  760. passed then the first reaction emoji used is returned.
  761.  
  762. This function returns the **first reaction that meets the requirements**.
  763.  
  764. Examples
  765. ---------
  766.  
  767. Basic Example:
  768.  
  769. .. code-block:: python
  770.  
  771. @client.event
  772. async def on_message(message):
  773. if message.content.startswith('$react'):
  774. msg = await client.send_message(message.channel, 'React with thumbs up or thumbs down.')
  775. res = await client.wait_for_reaction(['\N{THUMBS UP SIGN}', '\N{THUMBS DOWN SIGN}'], message=msg)
  776. await client.send_message(message.channel, '{0.user} reacted with {0.reaction.emoji}!'.format(res))
  777.  
  778. Checking for reaction emoji regardless of skin tone:
  779.  
  780. .. code-block:: python
  781.  
  782. @client.event
  783. async def on_message(message):
  784. if message.content.startswith('$react'):
  785. msg = await client.send_message(message.channel, 'React with thumbs up or thumbs down.')
  786.  
  787. def check(reaction, user):
  788. e = str(reaction.emoji)
  789. return e.startswith(('\N{THUMBS UP SIGN}', '\N{THUMBS DOWN SIGN}'))
  790.  
  791. res = await client.wait_for_reaction(message=msg, check=check)
  792. await client.send_message(message.channel, '{0.user} reacted with {0.reaction.emoji}!'.format(res))
  793.  
  794. Parameters
  795. -----------
  796. timeout: float
  797. The number of seconds to wait before returning ``None``.
  798. user: :class:`Member` or :class:`User`
  799. The user the reaction must be from.
  800. emoji: str or :class:`Emoji` or sequence
  801. The emoji that we are waiting to react with.
  802. message: :class:`Message`
  803. The message that we want the reaction to be from.
  804. check: function
  805. A predicate for other complicated checks. The predicate must take
  806. ``(reaction, user)`` as its two parameters, which ``reaction`` being a
  807. :class:`Reaction` and ``user`` being either a :class:`User` or a
  808. :class:`Member`.
  809.  
  810. Returns
  811. --------
  812. namedtuple
  813. A namedtuple with attributes ``reaction`` and ``user`` similar to :func:`on_reaction_add`.
  814. """
  815.  
  816. if emoji is None:
  817. emoji_check = lambda r: True
  818. elif isinstance(emoji, (str, Emoji)):
  819. emoji_check = lambda r: r.emoji == emoji
  820. else:
  821. emoji_check = lambda r: r.emoji in emoji
  822.  
  823. def predicate(reaction, reaction_user):
  824. result = emoji_check(reaction)
  825.  
  826. if message is not None:
  827. result = result and message.id == reaction.message.id
  828.  
  829. if user is not None:
  830. result = result and user.id == reaction_user.id
  831.  
  832. if callable(check):
  833. # the exception thrown by check is propagated through the future.
  834. result = result and check(reaction, reaction_user)
  835.  
  836. return result
  837.  
  838. future = asyncio.Future(loop=self.loop)
  839. self._listeners.append((predicate, future, WaitForType.reaction))
  840. try:
  841. return (yield from asyncio.wait_for(future, timeout, loop=self.loop))
  842. except asyncio.TimeoutError:
  843. return None
  844.  
  845. # event registration
  846.  
  847. def event(self, coro):
  848. """A decorator that registers an event to listen to.
  849.  
  850. You can find more info about the events on the :ref:`documentation below <discord-api-events>`.
  851.  
  852. The events must be a |corourl|_, if not, :exc:`ClientException` is raised.
  853.  
  854. Examples
  855. ---------
  856.  
  857. Using the basic :meth:`event` decorator: ::
  858.  
  859. @client.event
  860. @asyncio.coroutine
  861. def on_ready():
  862. print('Ready!')
  863.  
  864. Saving characters by using the :meth:`async_event` decorator: ::
  865.  
  866. @client.async_event
  867. def on_ready():
  868. print('Ready!')
  869.  
  870. """
  871.  
  872. if not asyncio.iscoroutinefunction(coro):
  873. raise ClientException('event registered must be a coroutine function')
  874.  
  875. setattr(self, coro.__name__, coro)
  876. log.info('{0.__name__} has successfully been registered as an event'.format(coro))
  877. return coro
  878.  
  879. def async_event(self, coro):
  880. """A shorthand decorator for ``asyncio.coroutine`` + :meth:`event`."""
  881. if not asyncio.iscoroutinefunction(coro):
  882. coro = asyncio.coroutine(coro)
  883.  
  884. return self.event(coro)
  885.  
  886. # Message sending/management
  887.  
  888. @asyncio.coroutine
  889. def start_private_message(self, user):
  890. """|coro|
  891.  
  892. Starts a private message with the user. This allows you to
  893. :meth:`send_message` to the user.
  894.  
  895. Note
  896. -----
  897. This method should rarely be called as :meth:`send_message`
  898. does it automatically for you.
  899.  
  900. Parameters
  901. -----------
  902. user : :class:`User`
  903. The user to start the private message with.
  904.  
  905. Raises
  906. ------
  907. HTTPException
  908. The request failed.
  909. InvalidArgument
  910. The user argument was not of :class:`User`.
  911. """
  912.  
  913. if not isinstance(user, User):
  914. raise InvalidArgument('user argument must be a User')
  915.  
  916. data = yield from self.http.start_private_message(user.id)
  917. channel = PrivateChannel(me=self.user, **data)
  918. self.connection._add_private_channel(channel)
  919. return channel
  920.  
  921. @asyncio.coroutine
  922. def add_reaction(self, message, emoji):
  923. """|coro|
  924.  
  925. Add a reaction to the given message.
  926.  
  927. The message must be a :class:`Message` that exists. emoji may be a unicode emoji,
  928. or a custom server :class:`Emoji`.
  929.  
  930. Parameters
  931. ------------
  932. message : :class:`Message`
  933. The message to react to.
  934. emoji : :class:`Emoji` or str
  935. The emoji to react with.
  936.  
  937. Raises
  938. --------
  939. HTTPException
  940. Adding the reaction failed.
  941. Forbidden
  942. You do not have the proper permissions to react to the message.
  943. NotFound
  944. The message or emoji you specified was not found.
  945. InvalidArgument
  946. The message or emoji parameter is invalid.
  947. """
  948. if not isinstance(message, Message):
  949. raise InvalidArgument('message argument must be a Message')
  950. if not isinstance(emoji, (str, Emoji)):
  951. raise InvalidArgument('emoji argument must be a string or Emoji')
  952.  
  953. if isinstance(emoji, Emoji):
  954. emoji = '{}:{}'.format(emoji.name, emoji.id)
  955.  
  956. yield from self.http.add_reaction(message.id, message.channel.id, emoji)
  957.  
  958. @asyncio.coroutine
  959. def remove_reaction(self, message, emoji, member):
  960. """|coro|
  961.  
  962. Remove a reaction by the member from the given message.
  963.  
  964. If member != server.me, you need Manage Messages to remove the reaction.
  965.  
  966. The message must be a :class:`Message` that exists. emoji may be a unicode emoji,
  967. or a custom server :class:`Emoji`.
  968.  
  969. Parameters
  970. ------------
  971. message : :class:`Message`
  972. The message.
  973. emoji : :class:`Emoji` or str
  974. The emoji to remove.
  975. member : :class:`Member`
  976. The member for which to delete the reaction.
  977.  
  978. Raises
  979. --------
  980. HTTPException
  981. Removing the reaction failed.
  982. Forbidden
  983. You do not have the proper permissions to remove the reaction.
  984. NotFound
  985. The message or emoji you specified was not found.
  986. InvalidArgument
  987. The message or emoji parameter is invalid.
  988. """
  989. if not isinstance(message, Message):
  990. raise InvalidArgument('message argument must be a Message')
  991. if not isinstance(emoji, (str, Emoji)):
  992. raise InvalidArgument('emoji must be a string or Emoji')
  993.  
  994. if isinstance(emoji, Emoji):
  995. emoji = '{}:{}'.format(emoji.name, emoji.id)
  996.  
  997. if member == self.user:
  998. member_id = '@me'
  999. else:
  1000. member_id = member.id
  1001.  
  1002. yield from self.http.remove_reaction(message.id, message.channel.id, emoji, member_id)
  1003.  
  1004. @asyncio.coroutine
  1005. def get_reaction_users(self, reaction, limit=100, after=None):
  1006. """|coro|
  1007.  
  1008. Get the users that added a reaction to a message.
  1009.  
  1010. Parameters
  1011. ------------
  1012. reaction : :class:`Reaction`
  1013. The reaction to retrieve users for.
  1014. limit : int
  1015. The maximum number of results to return.
  1016. after : :class:`Member` or :class:`Object`
  1017. For pagination, reactions are sorted by member.
  1018.  
  1019. Raises
  1020. --------
  1021. HTTPException
  1022. Getting the users for the reaction failed.
  1023. NotFound
  1024. The message or emoji you specified was not found.
  1025. InvalidArgument
  1026. The reaction parameter is invalid.
  1027. """
  1028. if not isinstance(reaction, Reaction):
  1029. raise InvalidArgument('reaction must be a Reaction')
  1030.  
  1031. emoji = reaction.emoji
  1032.  
  1033. if isinstance(emoji, Emoji):
  1034. emoji = '{}:{}'.format(emoji.name, emoji.id)
  1035.  
  1036. if after:
  1037. after = after.id
  1038.  
  1039. data = yield from self.http.get_reaction_users(
  1040. reaction.message.id, reaction.message.channel.id,
  1041. emoji, limit, after=after)
  1042.  
  1043. return [User(**user) for user in data]
  1044.  
  1045. @asyncio.coroutine
  1046. def clear_reactions(self, message):
  1047. """|coro|
  1048.  
  1049. Removes all the reactions from a given message.
  1050.  
  1051. You need Manage Messages permission to use this.
  1052.  
  1053. Parameters
  1054. -----------
  1055. message: :class:`Message`
  1056. The message to remove all reactions from.
  1057.  
  1058. Raises
  1059. --------
  1060. HTTPException
  1061. Removing the reactions failed.
  1062. Forbidden
  1063. You do not have the proper permissions to remove all the reactions.
  1064. """
  1065. yield from self.http.clear_reactions(message.id, message.channel.id)
  1066.  
  1067. @asyncio.coroutine
  1068. def send_message(self, destination, content=None, *, tts=False, embed=None):
  1069. """|coro|
  1070.  
  1071. Sends a message to the destination given with the content given.
  1072.  
  1073. The destination could be a :class:`Channel`, :class:`PrivateChannel` or :class:`Server`.
  1074. For convenience it could also be a :class:`User`. If it's a :class:`User` or :class:`PrivateChannel`
  1075. then it sends the message via private message, otherwise it sends the message to the channel.
  1076. If the destination is a :class:`Server` then it's equivalent to calling
  1077. :attr:`Server.default_channel` and sending it there.
  1078.  
  1079. If it is a :class:`Object` instance then it is assumed to be the
  1080. destination ID. The destination ID is a *channel* so passing in a user
  1081. ID will not be a valid destination.
  1082.  
  1083. .. versionchanged:: 0.9.0
  1084. ``str`` being allowed was removed and replaced with :class:`Object`.
  1085.  
  1086. The content must be a type that can convert to a string through ``str(content)``.
  1087. If the content is set to ``None`` (the default), then the ``embed`` parameter must
  1088. be provided.
  1089.  
  1090. If the ``embed`` parameter is provided, it must be of type :class:`Embed` and
  1091. it must be a rich embed type.
  1092.  
  1093. Parameters
  1094. ------------
  1095. destination
  1096. The location to send the message.
  1097. content
  1098. The content of the message to send. If this is missing,
  1099. then the ``embed`` parameter must be present.
  1100. tts : bool
  1101. Indicates if the message should be sent using text-to-speech.
  1102. embed: :class:`Embed`
  1103. The rich embed for the content.
  1104.  
  1105. Raises
  1106. --------
  1107. HTTPException
  1108. Sending the message failed.
  1109. Forbidden
  1110. You do not have the proper permissions to send the message.
  1111. NotFound
  1112. The destination was not found and hence is invalid.
  1113. InvalidArgument
  1114. The destination parameter is invalid.
  1115.  
  1116. Examples
  1117. ----------
  1118.  
  1119. Sending a regular message:
  1120.  
  1121. .. code-block:: python
  1122.  
  1123. await client.send_message(message.channel, 'Hello')
  1124.  
  1125. Sending a TTS message:
  1126.  
  1127. .. code-block:: python
  1128.  
  1129. await client.send_message(message.channel, 'Goodbye.', tts=True)
  1130.  
  1131. Sending an embed message:
  1132.  
  1133. .. code-block:: python
  1134.  
  1135. em = discord.Embed(title='My Embed Title', description='My Embed Content.', colour=0xDEADBF)
  1136. em.set_author(name='Someone', icon_url=client.user.default_avatar_url)
  1137. await client.send_message(message.channel, embed=em)
  1138.  
  1139. Returns
  1140. ---------
  1141. :class:`Message`
  1142. The message that was sent.
  1143. """
  1144.  
  1145. channel_id, guild_id = yield from self._resolve_destination(destination)
  1146.  
  1147. content = str(content) if content else None
  1148.  
  1149. if embed is not None:
  1150. embed = embed.to_dict()
  1151.  
  1152. data = yield from self.http.send_message(channel_id, content, guild_id=guild_id, tts=tts, embed=embed)
  1153. channel = self.get_channel(data.get('channel_id'))
  1154. message = self.connection._create_message(channel=channel, **data)
  1155. return message
  1156.  
  1157. @asyncio.coroutine
  1158. def send_typing(self, destination):
  1159. """|coro|
  1160.  
  1161. Send a *typing* status to the destination.
  1162.  
  1163. *Typing* status will go away after 10 seconds, or after a message is sent.
  1164.  
  1165. The destination parameter follows the same rules as :meth:`send_message`.
  1166.  
  1167. Parameters
  1168. ----------
  1169. destination
  1170. The location to send the typing update.
  1171. """
  1172.  
  1173. channel_id, guild_id = yield from self._resolve_destination(destination)
  1174. yield from self.http.send_typing(channel_id)
  1175.  
  1176. @asyncio.coroutine
  1177. def send_file(self, destination, fp, *, filename=None, content=None, tts=False):
  1178. """|coro|
  1179.  
  1180. Sends a message to the destination given with the file given.
  1181.  
  1182. The destination parameter follows the same rules as :meth:`send_message`.
  1183.  
  1184. The ``fp`` parameter should be either a string denoting the location for a
  1185. file or a *file-like object*. The *file-like object* passed is **not closed**
  1186. at the end of execution. You are responsible for closing it yourself.
  1187.  
  1188. .. note::
  1189.  
  1190. If the file-like object passed is opened via ``open`` then the modes
  1191. 'rb' should be used.
  1192.  
  1193. The ``filename`` parameter is the filename of the file.
  1194. If this is not given then it defaults to ``fp.name`` or if ``fp`` is a string
  1195. then the ``filename`` will default to the string given. You can overwrite
  1196. this value by passing this in.
  1197.  
  1198. Parameters
  1199. ------------
  1200. destination
  1201. The location to send the message.
  1202. fp
  1203. The *file-like object* or file path to send.
  1204. filename : str
  1205. The filename of the file. Defaults to ``fp.name`` if it's available.
  1206. content
  1207. The content of the message to send along with the file. This is
  1208. forced into a string by a ``str(content)`` call.
  1209. tts : bool
  1210. If the content of the message should be sent with TTS enabled.
  1211.  
  1212. Raises
  1213. -------
  1214. HTTPException
  1215. Sending the file failed.
  1216.  
  1217. Returns
  1218. --------
  1219. :class:`Message`
  1220. The message sent.
  1221. """
  1222.  
  1223. channel_id, guild_id = yield from self._resolve_destination(destination)
  1224.  
  1225. try:
  1226. with open(fp, 'rb') as f:
  1227. buffer = io.BytesIO(f.read())
  1228. if filename is None:
  1229. _, filename = path_split(fp)
  1230. except TypeError:
  1231. buffer = fp
  1232.  
  1233. data = yield from self.http.send_file(channel_id, buffer, guild_id=guild_id,
  1234. filename=filename, content=content, tts=tts)
  1235. channel = self.get_channel(data.get('channel_id'))
  1236. message = self.connection._create_message(channel=channel, **data)
  1237. return message
  1238.  
  1239. @asyncio.coroutine
  1240. def delete_message(self, message):
  1241. """|coro|
  1242.  
  1243. Deletes a :class:`Message`.
  1244.  
  1245. Your own messages could be deleted without any proper permissions. However to
  1246. delete other people's messages, you need the proper permissions to do so.
  1247.  
  1248. Parameters
  1249. -----------
  1250. message : :class:`Message`
  1251. The message to delete.
  1252.  
  1253. Raises
  1254. ------
  1255. Forbidden
  1256. You do not have proper permissions to delete the message.
  1257. HTTPException
  1258. Deleting the message failed.
  1259. """
  1260. channel = message.channel
  1261. guild_id = channel.server.id if not getattr(channel, 'is_private', True) else None
  1262. yield from self.http.delete_message(channel.id, message.id, guild_id)
  1263.  
  1264. @asyncio.coroutine
  1265. def delete_messages(self, messages):
  1266. """|coro|
  1267.  
  1268. Deletes a list of messages. This is similar to :func:`delete_message`
  1269. except it bulk deletes multiple messages.
  1270.  
  1271. The channel to check where the message is deleted from is handled via
  1272. the first element of the iterable's ``.channel.id`` attributes. If the
  1273. channel is not consistent throughout the entire sequence, then an
  1274. :exc:`HTTPException` will be raised.
  1275.  
  1276. Usable only by bot accounts.
  1277.  
  1278. Parameters
  1279. -----------
  1280. messages : iterable of :class:`Message`
  1281. An iterable of messages denoting which ones to bulk delete.
  1282.  
  1283. Raises
  1284. ------
  1285. ClientException
  1286. The number of messages to delete is less than 2 or more than 100.
  1287. Forbidden
  1288. You do not have proper permissions to delete the messages or
  1289. you're not using a bot account.
  1290. HTTPException
  1291. Deleting the messages failed.
  1292. """
  1293.  
  1294. messages = list(messages)
  1295. if len(messages) > 100 or len(messages) < 2:
  1296. raise ClientException('Can only delete messages in the range of [2, 100]')
  1297.  
  1298. channel = messages[0].channel
  1299. message_ids = [m.id for m in messages]
  1300. guild_id = channel.server.id if not getattr(channel, 'is_private', True) else None
  1301. yield from self.http.delete_messages(channel.id, message_ids, guild_id)
  1302.  
  1303. @asyncio.coroutine
  1304. def purge_from(self, channel, *, limit=100, check=None, before=None, after=None, around=None):
  1305. """|coro|
  1306.  
  1307. Purges a list of messages that meet the criteria given by the predicate
  1308. ``check``. If a ``check`` is not provided then all messages are deleted
  1309. without discrimination.
  1310.  
  1311. You must have Manage Messages permission to delete messages even if they
  1312. are your own. The Read Message History permission is also needed to
  1313. retrieve message history.
  1314.  
  1315. Usable only by bot accounts.
  1316.  
  1317. Parameters
  1318. -----------
  1319. channel : :class:`Channel`
  1320. The channel to purge from.
  1321. limit : int
  1322. The number of messages to search through. This is not the number
  1323. of messages that will be deleted, though it can be.
  1324. check : predicate
  1325. The function used to check if a message should be deleted.
  1326. It must take a :class:`Message` as its sole parameter.
  1327. before : :class:`Message` or `datetime`
  1328. The message or date before which all deleted messages must be.
  1329. If a date is provided it must be a timezone-naive datetime representing UTC time.
  1330. after : :class:`Message` or `datetime`
  1331. The message or date after which all deleted messages must be.
  1332. If a date is provided it must be a timezone-naive datetime representing UTC time.
  1333. around : :class:`Message` or `datetime`
  1334. The message or date around which all deleted messages must be.
  1335. If a date is provided it must be a timezone-naive datetime representing UTC time.
  1336.  
  1337. Raises
  1338. -------
  1339. Forbidden
  1340. You do not have proper permissions to do the actions required or
  1341. you're not using a bot account.
  1342. HTTPException
  1343. Purging the messages failed.
  1344.  
  1345. Examples
  1346. ---------
  1347.  
  1348. Deleting bot's messages ::
  1349.  
  1350. def is_me(m):
  1351. return m.author == client.user
  1352.  
  1353. deleted = await client.purge_from(channel, limit=100, check=is_me)
  1354. await client.send_message(channel, 'Deleted {} message(s)'.format(len(deleted)))
  1355.  
  1356. Returns
  1357. --------
  1358. list
  1359. The list of messages that were deleted.
  1360. """
  1361.  
  1362. if check is None:
  1363. check = lambda m: True
  1364.  
  1365. if isinstance(before, datetime.datetime):
  1366. before = Object(utils.time_snowflake(before, high=False))
  1367. if isinstance(after, datetime.datetime):
  1368. after = Object(utils.time_snowflake(after, high=True))
  1369. if isinstance(around, datetime.datetime):
  1370. around = Object(utils.time_snowflake(around, high=True))
  1371.  
  1372. iterator = LogsFromIterator(self, channel, limit, before=before, after=after, around=around)
  1373. ret = []
  1374. count = 0
  1375.  
  1376. while True:
  1377. try:
  1378. msg = yield from iterator.iterate()
  1379. except asyncio.QueueEmpty:
  1380. # no more messages to poll
  1381. if count >= 2:
  1382. # more than 2 messages -> bulk delete
  1383. to_delete = ret[-count:]
  1384. yield from self.delete_messages(to_delete)
  1385. elif count == 1:
  1386. # delete a single message
  1387. yield from self.delete_message(ret[-1])
  1388.  
  1389. return ret
  1390. else:
  1391. if count == 100:
  1392. # we've reached a full 'queue'
  1393. to_delete = ret[-100:]
  1394. yield from self.delete_messages(to_delete)
  1395. count = 0
  1396. yield from asyncio.sleep(1, loop=self.loop)
  1397.  
  1398. if check(msg):
  1399. count += 1
  1400. ret.append(msg)
  1401.  
  1402. @asyncio.coroutine
  1403. def edit_message(self, message, new_content=None, *, embed=None):
  1404. """|coro|
  1405.  
  1406. Edits a :class:`Message` with the new message content.
  1407.  
  1408. The new_content must be able to be transformed into a string via ``str(new_content)``.
  1409.  
  1410. If the ``new_content`` is not provided, then ``embed`` must be provided, which must
  1411. be of type :class:`Embed`.
  1412.  
  1413. The :class:`Message` object is not directly modified afterwards until the
  1414. corresponding WebSocket event is received.
  1415.  
  1416. Parameters
  1417. -----------
  1418. message : :class:`Message`
  1419. The message to edit.
  1420. new_content
  1421. The new content to replace the message with.
  1422. embed: :class:`Embed`
  1423. The new embed to replace the original embed with.
  1424.  
  1425. Raises
  1426. -------
  1427. HTTPException
  1428. Editing the message failed.
  1429.  
  1430. Returns
  1431. --------
  1432. :class:`Message`
  1433. The new edited message.
  1434. """
  1435.  
  1436. channel = message.channel
  1437. content = str(new_content) if new_content else None
  1438. embed = embed.to_dict() if embed else None
  1439. guild_id = channel.server.id if not getattr(channel, 'is_private', True) else None
  1440. data = yield from self.http.edit_message(message.id, channel.id, content, guild_id=guild_id, embed=embed)
  1441. return self.connection._create_message(channel=channel, **data)
  1442.  
  1443. @asyncio.coroutine
  1444. def get_message(self, channel, id):
  1445. """|coro|
  1446.  
  1447. Retrieves a single :class:`Message` from a :class:`Channel`.
  1448.  
  1449. This can only be used by bot accounts.
  1450.  
  1451. Parameters
  1452. ------------
  1453. channel: :class:`Channel` or :class:`PrivateChannel`
  1454. The text channel to retrieve the message from.
  1455. id: str
  1456. The message ID to look for.
  1457.  
  1458. Returns
  1459. --------
  1460. :class:`Message`
  1461. The message asked for.
  1462.  
  1463. Raises
  1464. --------
  1465. NotFound
  1466. The specified channel or message was not found.
  1467. Forbidden
  1468. You do not have the permissions required to get a message.
  1469. HTTPException
  1470. Retrieving the message failed.
  1471. """
  1472.  
  1473. data = yield from self.http.get_message(channel.id, id)
  1474. return self.connection._create_message(channel=channel, **data)
  1475.  
  1476. @asyncio.coroutine
  1477. def pin_message(self, message):
  1478. """|coro|
  1479.  
  1480. Pins a message. You must have Manage Messages permissions
  1481. to do this in a non-private channel context.
  1482.  
  1483. Parameters
  1484. -----------
  1485. message: :class:`Message`
  1486. The message to pin.
  1487.  
  1488. Raises
  1489. -------
  1490. Forbidden
  1491. You do not have permissions to pin the message.
  1492. NotFound
  1493. The message or channel was not found.
  1494. HTTPException
  1495. Pinning the message failed, probably due to the channel
  1496. having more than 50 pinned messages.
  1497. """
  1498. yield from self.http.pin_message(message.channel.id, message.id)
  1499.  
  1500. @asyncio.coroutine
  1501. def unpin_message(self, message):
  1502. """|coro|
  1503.  
  1504. Unpins a message. You must have Manage Messages permissions
  1505. to do this in a non-private channel context.
  1506.  
  1507. Parameters
  1508. -----------
  1509. message: :class:`Message`
  1510. The message to unpin.
  1511.  
  1512. Raises
  1513. -------
  1514. Forbidden
  1515. You do not have permissions to unpin the message.
  1516. NotFound
  1517. The message or channel was not found.
  1518. HTTPException
  1519. Unpinning the message failed.
  1520. """
  1521. yield from self.http.unpin_message(message.channel.id, message.id)
  1522.  
  1523. @asyncio.coroutine
  1524. def pins_from(self, channel):
  1525. """|coro|
  1526.  
  1527. Returns a list of :class:`Message` that are currently pinned for
  1528. the specified :class:`Channel` or :class:`PrivateChannel`.
  1529.  
  1530. Parameters
  1531. -----------
  1532. channel: :class:`Channel` or :class:`PrivateChannel`
  1533. The channel to look through pins for.
  1534.  
  1535. Raises
  1536. -------
  1537. NotFound
  1538. The channel was not found.
  1539. HTTPException
  1540. Retrieving the pinned messages failed.
  1541. """
  1542.  
  1543. data = yield from self.http.pins_from(channel.id)
  1544. return [self.connection._create_message(channel=channel, **m) for m in data]
  1545.  
  1546. def _logs_from(self, channel, limit=100, before=None, after=None, around=None):
  1547. """|coro|
  1548.  
  1549. This coroutine returns a generator that obtains logs from a specified channel.
  1550.  
  1551. Parameters
  1552. -----------
  1553. channel : :class:`Channel` or :class:`PrivateChannel`
  1554. The channel to obtain the logs from.
  1555. limit : int
  1556. The number of messages to retrieve.
  1557. before : :class:`Message` or `datetime`
  1558. The message or date before which all returned messages must be.
  1559. If a date is provided it must be a timezone-naive datetime representing UTC time.
  1560. after : :class:`Message` or `datetime`
  1561. The message or date after which all returned messages must be.
  1562. If a date is provided it must be a timezone-naive datetime representing UTC time.
  1563. around : :class:`Message` or `datetime`
  1564. The message or date around which all returned messages must be.
  1565. If a date is provided it must be a timezone-naive datetime representing UTC time.
  1566.  
  1567. Raises
  1568. ------
  1569. Forbidden
  1570. You do not have permissions to get channel logs.
  1571. NotFound
  1572. The channel you are requesting for doesn't exist.
  1573. HTTPException
  1574. The request to get logs failed.
  1575.  
  1576. Yields
  1577. -------
  1578. :class:`Message`
  1579. The message with the message data parsed.
  1580.  
  1581. Examples
  1582. ---------
  1583.  
  1584. Basic logging: ::
  1585.  
  1586. logs = yield from client.logs_from(channel)
  1587. for message in logs:
  1588. if message.content.startswith('!hello'):
  1589. if message.author == client.user:
  1590. yield from client.edit_message(message, 'goodbye')
  1591.  
  1592. Python 3.5 Usage ::
  1593.  
  1594. counter = 0
  1595. async for message in client.logs_from(channel, limit=500):
  1596. if message.author == client.user:
  1597. counter += 1
  1598. """
  1599. before = getattr(before, 'id', None)
  1600. after = getattr(after, 'id', None)
  1601. around = getattr(around, 'id', None)
  1602.  
  1603. return self.http.logs_from(channel.id, limit, before=before, after=after, around=around)
  1604.  
  1605. if PY35:
  1606. def logs_from(self, channel, limit=100, *, before=None, after=None, around=None, reverse=False):
  1607. if isinstance(before, datetime.datetime):
  1608. before = Object(utils.time_snowflake(before, high=False))
  1609. if isinstance(after, datetime.datetime):
  1610. after = Object(utils.time_snowflake(after, high=True))
  1611. if isinstance(around, datetime.datetime):
  1612. around = Object(utils.time_snowflake(around))
  1613.  
  1614. return LogsFromIterator(self, channel, limit, before=before, after=after, around=around, reverse=reverse)
  1615. else:
  1616. @asyncio.coroutine
  1617. def logs_from(self, channel, limit=100, *, before=None, after=None):
  1618. if isinstance(before, datetime.datetime):
  1619. before = Object(utils.time_snowflake(before, high=False))
  1620. if isinstance(after, datetime.datetime):
  1621. after = Object(utils.time_snowflake(after, high=True))
  1622.  
  1623. def generator(data):
  1624. for message in data:
  1625. yield self.connection._create_message(channel=channel, **message)
  1626.  
  1627. result = []
  1628. while limit > 0:
  1629. retrieve = limit if limit <= 100 else 100
  1630. data = yield from self._logs_from(channel, retrieve, before, after)
  1631. if len(data):
  1632. limit -= retrieve
  1633. result.extend(data)
  1634. before = Object(id=data[-1]['id'])
  1635. else:
  1636. break
  1637.  
  1638. return generator(result)
  1639.  
  1640. logs_from.__doc__ = _logs_from.__doc__
  1641.  
  1642. # Member management
  1643.  
  1644. @asyncio.coroutine
  1645. def request_offline_members(self, server):
  1646. """|coro|
  1647.  
  1648. Requests previously offline members from the server to be filled up
  1649. into the :attr:`Server.members` cache. This function is usually not
  1650. called.
  1651.  
  1652. When the client logs on and connects to the websocket, Discord does
  1653. not provide the library with offline members if the number of members
  1654. in the server is larger than 250. You can check if a server is large
  1655. if :attr:`Server.large` is ``True``.
  1656.  
  1657. Parameters
  1658. -----------
  1659. server : :class:`Server` or iterable
  1660. The server to request offline members for. If this parameter is a
  1661. iterable then it is interpreted as an iterator of servers to
  1662. request offline members for.
  1663. """
  1664.  
  1665. if hasattr(server, 'id'):
  1666. guild_id = server.id
  1667. else:
  1668. guild_id = [s.id for s in server]
  1669.  
  1670. payload = {
  1671. 'op': 8,
  1672. 'd': {
  1673. 'guild_id': guild_id,
  1674. 'query': '',
  1675. 'limit': 0
  1676. }
  1677. }
  1678.  
  1679. yield from self.ws.send_as_json(payload)
  1680.  
  1681. @asyncio.coroutine
  1682. def kick(self, member):
  1683. """|coro|
  1684.  
  1685. Kicks a :class:`Member` from the server they belong to.
  1686.  
  1687. Warning
  1688. --------
  1689. This function kicks the :class:`Member` based on the server it
  1690. belongs to, which is accessed via :attr:`Member.server`. So you
  1691. must have the proper permissions in that server.
  1692.  
  1693. Parameters
  1694. -----------
  1695. member : :class:`Member`
  1696. The member to kick from their server.
  1697.  
  1698. Raises
  1699. -------
  1700. Forbidden
  1701. You do not have the proper permissions to kick.
  1702. HTTPException
  1703. Kicking failed.
  1704. """
  1705. yield from self.http.kick(member.id, member.server.id)
  1706.  
  1707. @asyncio.coroutine
  1708. def ban(self, member, delete_message_days=1):
  1709. """|coro|
  1710.  
  1711. Bans a :class:`Member` from the server they belong to.
  1712.  
  1713. Warning
  1714. --------
  1715. This function bans the :class:`Member` based on the server it
  1716. belongs to, which is accessed via :attr:`Member.server`. So you
  1717. must have the proper permissions in that server.
  1718.  
  1719. Parameters
  1720. -----------
  1721. member : :class:`Member`
  1722. The member to ban from their server.
  1723. delete_message_days : int
  1724. The number of days worth of messages to delete from the user
  1725. in the server. The minimum is 0 and the maximum is 7.
  1726.  
  1727. Raises
  1728. -------
  1729. Forbidden
  1730. You do not have the proper permissions to ban.
  1731. HTTPException
  1732. Banning failed.
  1733. """
  1734. yield from self.http.ban(member.id, member.server.id, delete_message_days)
  1735.  
  1736. @asyncio.coroutine
  1737. def unban(self, server, user):
  1738. """|coro|
  1739.  
  1740. Unbans a :class:`User` from the server they are banned from.
  1741.  
  1742. Parameters
  1743. -----------
  1744. server : :class:`Server`
  1745. The server to unban the user from.
  1746. user : :class:`User`
  1747. The user to unban.
  1748.  
  1749. Raises
  1750. -------
  1751. Forbidden
  1752. You do not have the proper permissions to unban.
  1753. HTTPException
  1754. Unbanning failed.
  1755. """
  1756. yield from self.http.unban(user.id, server.id)
  1757.  
  1758. @asyncio.coroutine
  1759. def server_voice_state(self, member, *, mute=None, deafen=None):
  1760. """|coro|
  1761.  
  1762. Server mutes or deafens a specific :class:`Member`.
  1763.  
  1764. Warning
  1765. --------
  1766. This function mutes or un-deafens the :class:`Member` based on the
  1767. server it belongs to, which is accessed via :attr:`Member.server`.
  1768. So you must have the proper permissions in that server.
  1769.  
  1770. Parameters
  1771. -----------
  1772. member : :class:`Member`
  1773. The member to unban from their server.
  1774. mute: Optional[bool]
  1775. Indicates if the member should be server muted or un-muted.
  1776. deafen: Optional[bool]
  1777. Indicates if the member should be server deafened or un-deafened.
  1778.  
  1779. Raises
  1780. -------
  1781. Forbidden
  1782. You do not have the proper permissions to deafen or mute.
  1783. HTTPException
  1784. The operation failed.
  1785. """
  1786. yield from self.http.server_voice_state(member.id, member.server.id, mute=mute, deafen=deafen)
  1787.  
  1788. @asyncio.coroutine
  1789. def edit_profile(self, password=None, **fields):
  1790. """|coro|
  1791.  
  1792. Edits the current profile of the client.
  1793.  
  1794. If a bot account is used then the password field is optional,
  1795. otherwise it is required.
  1796.  
  1797. The :attr:`Client.user` object is not modified directly afterwards until the
  1798. corresponding WebSocket event is received.
  1799.  
  1800. Note
  1801. -----
  1802. To upload an avatar, a *bytes-like object* must be passed in that
  1803. represents the image being uploaded. If this is done through a file
  1804. then the file must be opened via ``open('some_filename', 'rb')`` and
  1805. the *bytes-like object* is given through the use of ``fp.read()``.
  1806.  
  1807. The only image formats supported for uploading is JPEG and PNG.
  1808.  
  1809. Parameters
  1810. -----------
  1811. password : str
  1812. The current password for the client's account. Not used
  1813. for bot accounts.
  1814. new_password : str
  1815. The new password you wish to change to.
  1816. email : str
  1817. The new email you wish to change to.
  1818. username :str
  1819. The new username you wish to change to.
  1820. avatar : bytes
  1821. A *bytes-like object* representing the image to upload.
  1822. Could be ``None`` to denote no avatar.
  1823.  
  1824. Raises
  1825. ------
  1826. HTTPException
  1827. Editing your profile failed.
  1828. InvalidArgument
  1829. Wrong image format passed for ``avatar``.
  1830. ClientException
  1831. Password is required for non-bot accounts.
  1832. """
  1833.  
  1834. try:
  1835. avatar_bytes = fields['avatar']
  1836. except KeyError:
  1837. avatar = self.user.avatar
  1838. else:
  1839. if avatar_bytes is not None:
  1840. avatar = utils._bytes_to_base64_data(avatar_bytes)
  1841. else:
  1842. avatar = None
  1843.  
  1844. not_bot_account = not self.user.bot
  1845. if not_bot_account and password is None:
  1846. raise ClientException('Password is required for non-bot accounts.')
  1847.  
  1848. args = {
  1849. 'password': password,
  1850. 'username': fields.get('username', self.user.name),
  1851. 'avatar': avatar
  1852. }
  1853.  
  1854. if not_bot_account:
  1855. args['email'] = fields.get('email', self.email)
  1856.  
  1857. if 'new_password' in fields:
  1858. args['new_password'] = fields['new_password']
  1859.  
  1860. data = yield from self.http.edit_profile(**args)
  1861. if not_bot_account:
  1862. self.email = data['email']
  1863. if 'token' in data:
  1864. self.http._token(data['token'], bot=False)
  1865.  
  1866. if self.cache_auth:
  1867. self._update_cache(self.email, password)
  1868.  
  1869. @asyncio.coroutine
  1870. @utils.deprecated('change_presence')
  1871. def change_status(self, game=None, idle=False):
  1872. """|coro|
  1873.  
  1874. Changes the client's status.
  1875.  
  1876. The game parameter is a Game object (not a string) that represents
  1877. a game being played currently.
  1878.  
  1879. The idle parameter is a boolean parameter that indicates whether the
  1880. client should go idle or not.
  1881.  
  1882. .. deprecated:: v0.13.0
  1883. Use :meth:`change_presence` instead.
  1884.  
  1885. Parameters
  1886. ----------
  1887. game : Optional[:class:`Game`]
  1888. The game being played. None if no game is being played.
  1889. idle : bool
  1890. Indicates if the client should go idle.
  1891.  
  1892. Raises
  1893. ------
  1894. InvalidArgument
  1895. If the ``game`` parameter is not :class:`Game` or None.
  1896. """
  1897. yield from self.ws.change_presence(game=game, idle=idle)
  1898.  
  1899. @asyncio.coroutine
  1900. def change_presence(self, *, game=None, status=None, afk=False):
  1901. """|coro|
  1902.  
  1903. Changes the client's presence.
  1904.  
  1905. The game parameter is a Game object (not a string) that represents
  1906. a game being played currently.
  1907.  
  1908. Parameters
  1909. ----------
  1910. game: Optional[:class:`Game`]
  1911. The game being played. None if no game is being played.
  1912. status: Optional[:class:`Status`]
  1913. Indicates what status to change to. If None, then
  1914. :attr:`Status.online` is used.
  1915. afk: bool
  1916. Indicates if you are going AFK. This allows the discord
  1917. client to know how to handle push notifications better
  1918. for you in case you are actually idle and not lying.
  1919.  
  1920. Raises
  1921. ------
  1922. InvalidArgument
  1923. If the ``game`` parameter is not :class:`Game` or None.
  1924. """
  1925.  
  1926. if status is None:
  1927. status = 'online'
  1928. elif status is Status.offline:
  1929. status = 'invisible'
  1930. else:
  1931. status = str(status)
  1932.  
  1933. yield from self.ws.change_presence(game=game, status=status, afk=afk)
  1934.  
  1935. @asyncio.coroutine
  1936. def change_nickname(self, member, nickname):
  1937. """|coro|
  1938.  
  1939. Changes a member's nickname.
  1940.  
  1941. You must have the proper permissions to change someone's
  1942. (or your own) nickname.
  1943.  
  1944. Parameters
  1945. ----------
  1946. member : :class:`Member`
  1947. The member to change the nickname for.
  1948. nickname : Optional[str]
  1949. The nickname to change it to. ``None`` to remove
  1950. the nickname.
  1951.  
  1952. Raises
  1953. ------
  1954. Forbidden
  1955. You do not have permissions to change the nickname.
  1956. HTTPException
  1957. Changing the nickname failed.
  1958. """
  1959.  
  1960. nickname = nickname if nickname else ''
  1961.  
  1962. if member == self.user:
  1963. yield from self.http.change_my_nickname(member.server.id, nickname)
  1964. else:
  1965. yield from self.http.change_nickname(member.server.id, member.id, nickname)
  1966.  
  1967. # Channel management
  1968.  
  1969. @asyncio.coroutine
  1970. def edit_channel(self, channel, **options):
  1971. """|coro|
  1972.  
  1973. Edits a :class:`Channel`.
  1974.  
  1975. You must have the proper permissions to edit the channel.
  1976.  
  1977. To move the channel's position use :meth:`move_channel` instead.
  1978.  
  1979. The :class:`Channel` object is not directly modified afterwards until the
  1980. corresponding WebSocket event is received.
  1981.  
  1982. Parameters
  1983. ----------
  1984. channel : :class:`Channel`
  1985. The channel to update.
  1986. name : str
  1987. The new channel name.
  1988. topic : str
  1989. The new channel's topic.
  1990. bitrate : int
  1991. The new channel's bitrate. Voice only.
  1992. user_limit : int
  1993. The new channel's user limit. Voice only.
  1994.  
  1995. Raises
  1996. ------
  1997. Forbidden
  1998. You do not have permissions to edit the channel.
  1999. HTTPException
  2000. Editing the channel failed.
  2001. """
  2002.  
  2003. keys = ('name', 'topic', 'position')
  2004. for key in keys:
  2005. if key not in options:
  2006. options[key] = getattr(channel, key)
  2007.  
  2008. yield from self.http.edit_channel(channel.id, **options)
  2009.  
  2010. @asyncio.coroutine
  2011. def move_channel(self, channel, position):
  2012. """|coro|
  2013.  
  2014. Moves the specified :class:`Channel` to the given position in the GUI.
  2015. Note that voice channels and text channels have different position values.
  2016.  
  2017. The :class:`Channel` object is not directly modified afterwards until the
  2018. corresponding WebSocket event is received.
  2019.  
  2020. .. warning::
  2021.  
  2022. :class:`Object` instances do not work with this function.
  2023.  
  2024. Parameters
  2025. -----------
  2026. channel : :class:`Channel`
  2027. The channel to change positions of.
  2028. position : int
  2029. The position to insert the channel to.
  2030.  
  2031. Raises
  2032. -------
  2033. InvalidArgument
  2034. If position is less than 0 or greater than the number of channels.
  2035. Forbidden
  2036. You do not have permissions to change channel order.
  2037. HTTPException
  2038. If moving the channel failed, or you are of too low rank to move the channel.
  2039. """
  2040.  
  2041. if position < 0:
  2042. raise InvalidArgument('Channel position cannot be less than 0.')
  2043.  
  2044. url = '{0}/{1.server.id}/channels'.format(self.http.GUILDS, channel)
  2045. channels = [c for c in channel.server.channels if c.type is channel.type]
  2046.  
  2047. if position >= len(channels):
  2048. raise InvalidArgument('Channel position cannot be greater than {}'.format(len(channels) - 1))
  2049.  
  2050. channels.sort(key=lambda c: c.position)
  2051.  
  2052. try:
  2053. # remove ourselves from the channel list
  2054. channels.remove(channel)
  2055. except ValueError:
  2056. # not there somehow lol
  2057. return
  2058. else:
  2059. # add ourselves at our designated position
  2060. channels.insert(position, channel)
  2061.  
  2062. payload = [{'id': c.id, 'position': index } for index, c in enumerate(channels)]
  2063. yield from self.http.patch(url, json=payload, bucket='move_channel')
  2064.  
  2065. @asyncio.coroutine
  2066. def create_channel(self, server, name, *overwrites, type=None):
  2067. """|coro|
  2068.  
  2069. Creates a :class:`Channel` in the specified :class:`Server`.
  2070.  
  2071. Note that you need the proper permissions to create the channel.
  2072.  
  2073. The ``overwrites`` argument list can be used to create a 'secret'
  2074. channel upon creation. A namedtuple of :class:`ChannelPermissions`
  2075. is exposed to create a channel-specific permission overwrite in a more
  2076. self-documenting matter. You can also use a regular tuple of ``(target, overwrite)``
  2077. where the ``overwrite`` expected has to be of type :class:`PermissionOverwrite`.
  2078.  
  2079. Examples
  2080. ----------
  2081.  
  2082. Creating a voice channel:
  2083.  
  2084. .. code-block:: python
  2085.  
  2086. await client.create_channel(server, 'Voice', type=discord.ChannelType.voice)
  2087.  
  2088. Creating a 'secret' text channel:
  2089.  
  2090. .. code-block:: python
  2091.  
  2092. everyone_perms = discord.PermissionOverwrite(read_messages=False)
  2093. my_perms = discord.PermissionOverwrite(read_messages=True)
  2094.  
  2095. everyone = discord.ChannelPermissions(target=server.default_role, overwrite=everyone_perms)
  2096. mine = discord.ChannelPermissions(target=server.me, overwrite=my_perms)
  2097. await client.create_channel(server, 'secret', everyone, mine)
  2098.  
  2099. Or in a more 'compact' way:
  2100.  
  2101. .. code-block:: python
  2102.  
  2103. everyone = discord.PermissionOverwrite(read_messages=False)
  2104. mine = discord.PermissionOverwrite(read_messages=True)
  2105. await client.create_channel(server, 'secret', (server.default_role, everyone), (server.me, mine))
  2106.  
  2107. Parameters
  2108. -----------
  2109. server : :class:`Server`
  2110. The server to create the channel in.
  2111. name : str
  2112. The channel's name.
  2113. type : :class:`ChannelType`
  2114. The type of channel to create. Defaults to :attr:`ChannelType.text`.
  2115. overwrites:
  2116. An argument list of channel specific overwrites to apply on the channel on
  2117. creation. Useful for creating 'secret' channels.
  2118.  
  2119. Raises
  2120. -------
  2121. Forbidden
  2122. You do not have the proper permissions to create the channel.
  2123. NotFound
  2124. The server specified was not found.
  2125. HTTPException
  2126. Creating the channel failed.
  2127. InvalidArgument
  2128. The permission overwrite array is not in proper form.
  2129.  
  2130. Returns
  2131. -------
  2132. :class:`Channel`
  2133. The channel that was just created. This channel is
  2134. different than the one that will be added in cache.
  2135. """
  2136.  
  2137. if type is None:
  2138. type = ChannelType.text
  2139.  
  2140. perms = []
  2141. for overwrite in overwrites:
  2142. target = overwrite[0]
  2143. perm = overwrite[1]
  2144. if not isinstance(perm, PermissionOverwrite):
  2145. raise InvalidArgument('Expected PermissionOverwrite received {0.__name__}'.format(type(perm)))
  2146.  
  2147. allow, deny = perm.pair()
  2148. payload = {
  2149. 'allow': allow.value,
  2150. 'deny': deny.value,
  2151. 'id': target.id
  2152. }
  2153.  
  2154. if isinstance(target, User):
  2155. payload['type'] = 'member'
  2156. elif isinstance(target, Role):
  2157. payload['type'] = 'role'
  2158. else:
  2159. raise InvalidArgument('Expected Role, User, or Member target, received {0.__name__}'.format(type(target)))
  2160.  
  2161. perms.append(payload)
  2162.  
  2163. data = yield from self.http.create_channel(server.id, name, str(type), permission_overwrites=perms)
  2164. channel = Channel(server=server, **data)
  2165. return channel
  2166.  
  2167. @asyncio.coroutine
  2168. def delete_channel(self, channel):
  2169. """|coro|
  2170.  
  2171. Deletes a :class:`Channel`.
  2172.  
  2173. In order to delete the channel, the client must have the proper permissions
  2174. in the server the channel belongs to.
  2175.  
  2176. Parameters
  2177. ------------
  2178. channel : :class:`Channel`
  2179. The channel to delete.
  2180.  
  2181. Raises
  2182. -------
  2183. Forbidden
  2184. You do not have proper permissions to delete the channel.
  2185. NotFound
  2186. The specified channel was not found.
  2187. HTTPException
  2188. Deleting the channel failed.
  2189. """
  2190. yield from self.http.delete_channel(channel.id)
  2191.  
  2192. # Server management
  2193.  
  2194. @asyncio.coroutine
  2195. def leave_server(self, server):
  2196. """|coro|
  2197.  
  2198. Leaves a :class:`Server`.
  2199.  
  2200. Note
  2201. --------
  2202. You cannot leave the server that you own, you must delete it instead
  2203. via :meth:`delete_server`.
  2204.  
  2205. Parameters
  2206. ----------
  2207. server : :class:`Server`
  2208. The server to leave.
  2209.  
  2210. Raises
  2211. --------
  2212. HTTPException
  2213. If leaving the server failed.
  2214. """
  2215. yield from self.http.leave_server(server.id)
  2216.  
  2217. @asyncio.coroutine
  2218. def delete_server(self, server):
  2219. """|coro|
  2220.  
  2221. Deletes a :class:`Server`. You must be the server owner to delete the
  2222. server.
  2223.  
  2224. Parameters
  2225. ----------
  2226. server : :class:`Server`
  2227. The server to delete.
  2228.  
  2229. Raises
  2230. --------
  2231. HTTPException
  2232. If deleting the server failed.
  2233. Forbidden
  2234. You do not have permissions to delete the server.
  2235. """
  2236.  
  2237. yield from self.http.delete_server(server.id)
  2238.  
  2239. @asyncio.coroutine
  2240. def create_server(self, name, region=None, icon=None):
  2241. """|coro|
  2242.  
  2243. Creates a :class:`Server`.
  2244.  
  2245. Parameters
  2246. ----------
  2247. name : str
  2248. The name of the server.
  2249. region : :class:`ServerRegion`
  2250. The region for the voice communication server.
  2251. Defaults to :attr:`ServerRegion.us_west`.
  2252. icon : bytes
  2253. The *bytes-like* object representing the icon. See :meth:`edit_profile`
  2254. for more details on what is expected.
  2255.  
  2256. Raises
  2257. ------
  2258. HTTPException
  2259. Server creation failed.
  2260. InvalidArgument
  2261. Invalid icon image format given. Must be PNG or JPG.
  2262.  
  2263. Returns
  2264. -------
  2265. :class:`Server`
  2266. The server created. This is not the same server that is
  2267. added to cache.
  2268. """
  2269. if icon is not None:
  2270. icon = utils._bytes_to_base64_data(icon)
  2271.  
  2272. if region is None:
  2273. region = ServerRegion.us_west.name
  2274. else:
  2275. region = region.name
  2276.  
  2277. data = yield from self.http.create_server(name, region, icon)
  2278. return Server(**data)
  2279.  
  2280. @asyncio.coroutine
  2281. def edit_server(self, server, **fields):
  2282. """|coro|
  2283.  
  2284. Edits a :class:`Server`.
  2285.  
  2286. You must have the proper permissions to edit the server.
  2287.  
  2288. The :class:`Server` object is not directly modified afterwards until the
  2289. corresponding WebSocket event is received.
  2290.  
  2291. Parameters
  2292. ----------
  2293. server: :class:`Server`
  2294. The server to edit.
  2295. name: str
  2296. The new name of the server.
  2297. icon: bytes
  2298. A *bytes-like* object representing the icon. See :meth:`edit_profile`
  2299. for more details. Could be ``None`` to denote no icon.
  2300. splash: bytes
  2301. A *bytes-like* object representing the invite splash. See
  2302. :meth:`edit_profile` for more details. Could be ``None`` to denote
  2303. no invite splash. Only available for partnered servers with
  2304. ``INVITE_SPLASH`` feature.
  2305. region: :class:`ServerRegion`
  2306. The new region for the server's voice communication.
  2307. afk_channel: :class:`Channel`
  2308. The new channel that is the AFK channel. Could be ``None`` for no AFK channel.
  2309. afk_timeout: int
  2310. The number of seconds until someone is moved to the AFK channel.
  2311. owner: :class:`Member`
  2312. The new owner of the server to transfer ownership to. Note that you must
  2313. be owner of the server to do this.
  2314. verification_level: :class:`VerificationLevel`
  2315. The new verification level for the server.
  2316.  
  2317. Raises
  2318. -------
  2319. Forbidden
  2320. You do not have permissions to edit the server.
  2321. NotFound
  2322. The server you are trying to edit does not exist.
  2323. HTTPException
  2324. Editing the server failed.
  2325. InvalidArgument
  2326. The image format passed in to ``icon`` is invalid. It must be
  2327. PNG or JPG. This is also raised if you are not the owner of the
  2328. server and request an ownership transfer.
  2329. """
  2330.  
  2331. try:
  2332. icon_bytes = fields['icon']
  2333. except KeyError:
  2334. icon = server.icon
  2335. else:
  2336. if icon_bytes is not None:
  2337. icon = utils._bytes_to_base64_data(icon_bytes)
  2338. else:
  2339. icon = None
  2340.  
  2341. try:
  2342. splash_bytes = fields['splash']
  2343. except KeyError:
  2344. splash = server.splash
  2345. else:
  2346. if splash_bytes is not None:
  2347. splash = utils._bytes_to_base64_data(splash_bytes)
  2348. else:
  2349. splash = None
  2350.  
  2351. fields['icon'] = icon
  2352. fields['splash'] = splash
  2353. if 'afk_channel' in fields:
  2354. fields['afk_channel_id'] = fields['afk_channel'].id
  2355.  
  2356. if 'owner' in fields:
  2357. if server.owner != server.me:
  2358. raise InvalidArgument('To transfer ownership you must be the owner of the server.')
  2359.  
  2360. fields['owner_id'] = fields['owner'].id
  2361.  
  2362. if 'region' in fields:
  2363. fields['region'] = str(fields['region'])
  2364.  
  2365. level = fields.get('verification_level', server.verification_level)
  2366. if not isinstance(level, VerificationLevel):
  2367. raise InvalidArgument('verification_level field must of type VerificationLevel')
  2368.  
  2369. fields['verification_level'] = level.value
  2370. yield from self.http.edit_server(server.id, **fields)
  2371.  
  2372. @asyncio.coroutine
  2373. def get_bans(self, server):
  2374. """|coro|
  2375.  
  2376. Retrieves all the :class:`User` s that are banned from the specified
  2377. server.
  2378.  
  2379. You must have proper permissions to get this information.
  2380.  
  2381. Parameters
  2382. ----------
  2383. server : :class:`Server`
  2384. The server to get ban information from.
  2385.  
  2386. Raises
  2387. -------
  2388. Forbidden
  2389. You do not have proper permissions to get the information.
  2390. HTTPException
  2391. An error occurred while fetching the information.
  2392.  
  2393. Returns
  2394. --------
  2395. list
  2396. A list of :class:`User` that have been banned.
  2397. """
  2398.  
  2399. data = yield from self.http.get_bans(server.id)
  2400. return [User(**user['user']) for user in data]
  2401.  
  2402. @asyncio.coroutine
  2403. def prune_members(self, server, *, days):
  2404. """|coro|
  2405.  
  2406. Prunes a :class:`Server` from its inactive members.
  2407.  
  2408. The inactive members are denoted if they have not logged on in
  2409. ``days`` number of days and they have no roles.
  2410.  
  2411. You must have the "Kick Members" permission to use this.
  2412.  
  2413. To check how many members you would prune without actually pruning,
  2414. see the :meth:`estimate_pruned_members` function.
  2415.  
  2416. Parameters
  2417. -----------
  2418. server: :class:`Server`
  2419. The server to prune from.
  2420. days: int
  2421. The number of days before counting as inactive.
  2422.  
  2423. Raises
  2424. -------
  2425. Forbidden
  2426. You do not have permissions to prune members.
  2427. HTTPException
  2428. An error occurred while pruning members.
  2429. InvalidArgument
  2430. An integer was not passed for ``days``.
  2431.  
  2432. Returns
  2433. ---------
  2434. int
  2435. The number of members pruned.
  2436. """
  2437.  
  2438. if not isinstance(days, int):
  2439. raise InvalidArgument('Expected int for ``days``, received {0.__class__.__name__} instead.'.format(days))
  2440.  
  2441. data = yield from self.http.prune_members(server.id, days)
  2442. return data['pruned']
  2443.  
  2444. @asyncio.coroutine
  2445. def estimate_pruned_members(self, server, *, days):
  2446. """|coro|
  2447.  
  2448. Similar to :meth:`prune_members` except instead of actually
  2449. pruning members, it returns how many members it would prune
  2450. from the server had it been called.
  2451.  
  2452. Parameters
  2453. -----------
  2454. server: :class:`Server`
  2455. The server to estimate a prune from.
  2456. days: int
  2457. The number of days before counting as inactive.
  2458.  
  2459. Raises
  2460. -------
  2461. Forbidden
  2462. You do not have permissions to prune members.
  2463. HTTPException
  2464. An error occurred while fetching the prune members estimate.
  2465. InvalidArgument
  2466. An integer was not passed for ``days``.
  2467.  
  2468. Returns
  2469. ---------
  2470. int
  2471. The number of members estimated to be pruned.
  2472. """
  2473.  
  2474. if not isinstance(days, int):
  2475. raise InvalidArgument('Expected int for ``days``, received {0.__class__.__name__} instead.'.format(days))
  2476.  
  2477. data = yield from self.http.estimate_pruned_members(server.id, days)
  2478. return data['pruned']
  2479.  
  2480. @asyncio.coroutine
  2481. def create_custom_emoji(self, server, *, name, image):
  2482. """|coro|
  2483.  
  2484. Creates a custom :class:`Emoji` for a :class:`Server`.
  2485.  
  2486. This endpoint is only allowed for user bots or white listed
  2487. bots. If this is done by a user bot then this is a local
  2488. emoji that can only be used inside that server.
  2489.  
  2490. There is currently a limit of 50 local emotes per server.
  2491.  
  2492. Parameters
  2493. -----------
  2494. server: :class:`Server`
  2495. The server to add the emoji to.
  2496. name: str
  2497. The emoji name. Must be at least 2 characters.
  2498. image: bytes
  2499. The *bytes-like* object representing the image data to use.
  2500. Only JPG and PNG images are supported.
  2501.  
  2502. Returns
  2503. --------
  2504. :class:`Emoji`
  2505. The created emoji.
  2506.  
  2507. Raises
  2508. -------
  2509. Forbidden
  2510. You are not allowed to create emojis.
  2511. HTTPException
  2512. An error occurred creating an emoji.
  2513. """
  2514.  
  2515. img = utils._bytes_to_base64_data(image)
  2516. data = yield from self.http.create_custom_emoji(server.id, name, img)
  2517. return Emoji(server=server, **data)
  2518.  
  2519. @asyncio.coroutine
  2520. def delete_custom_emoji(self, emoji):
  2521. """|coro|
  2522.  
  2523. Deletes a custom :class:`Emoji` from a :class:`Server`.
  2524.  
  2525. This follows the same rules as :meth:`create_custom_emoji`.
  2526.  
  2527. Parameters
  2528. -----------
  2529. emoji: :class:`Emoji`
  2530. The emoji to delete.
  2531.  
  2532. Raises
  2533. -------
  2534. Forbidden
  2535. You are not allowed to delete emojis.
  2536. HTTPException
  2537. An error occurred deleting the emoji.
  2538. """
  2539.  
  2540. yield from self.http.delete_custom_emoji(emoji.server.id, emoji.id)
  2541.  
  2542. @asyncio.coroutine
  2543. def edit_custom_emoji(self, emoji, *, name):
  2544. """|coro|
  2545.  
  2546. Edits a :class:`Emoji`.
  2547.  
  2548. Parameters
  2549. -----------
  2550. emoji: :class:`Emoji`
  2551. The emoji to edit.
  2552. name: str
  2553. The new emoji name.
  2554.  
  2555. Raises
  2556. -------
  2557. Forbidden
  2558. You are not allowed to edit emojis.
  2559. HTTPException
  2560. An error occurred editing the emoji.
  2561. """
  2562.  
  2563. yield from self.http.edit_custom_emoji(emoji.server.id, emoji.id, name=name)
  2564.  
  2565.  
  2566. # Invite management
  2567.  
  2568. def _fill_invite_data(self, data):
  2569. server = self.connection._get_server(data['guild']['id'])
  2570. if server is not None:
  2571. ch_id = data['channel']['id']
  2572. channel = server.get_channel(ch_id)
  2573. else:
  2574. server = Object(id=data['guild']['id'])
  2575. server.name = data['guild']['name']
  2576. channel = Object(id=data['channel']['id'])
  2577. channel.name = data['channel']['name']
  2578. data['server'] = server
  2579. data['channel'] = channel
  2580.  
  2581. @asyncio.coroutine
  2582. def create_invite(self, destination, **options):
  2583. """|coro|
  2584.  
  2585. Creates an invite for the destination which could be either a
  2586. :class:`Server` or :class:`Channel`.
  2587.  
  2588. Parameters
  2589. ------------
  2590. destination
  2591. The :class:`Server` or :class:`Channel` to create the invite to.
  2592. max_age : int
  2593. How long the invite should last. If it's 0 then the invite
  2594. doesn't expire. Defaults to 0.
  2595. max_uses : int
  2596. How many uses the invite could be used for. If it's 0 then there
  2597. are unlimited uses. Defaults to 0.
  2598. temporary : bool
  2599. Denotes that the invite grants temporary membership
  2600. (i.e. they get kicked after they disconnect). Defaults to False.
  2601. xkcd : bool
  2602. Indicates if the invite URL is human readable. Defaults to False.
  2603.  
  2604. Raises
  2605. -------
  2606. HTTPException
  2607. Invite creation failed.
  2608.  
  2609. Returns
  2610. --------
  2611. :class:`Invite`
  2612. The invite that was created.
  2613. """
  2614.  
  2615. data = yield from self.http.create_invite(destination.id, **options)
  2616. self._fill_invite_data(data)
  2617. return Invite(**data)
  2618.  
  2619. @asyncio.coroutine
  2620. def get_invite(self, url):
  2621. """|coro|
  2622.  
  2623. Gets a :class:`Invite` from a discord.gg URL or ID.
  2624.  
  2625. Note
  2626. ------
  2627. If the invite is for a server you have not joined, the server and channel
  2628. attributes of the returned invite will be :class:`Object` with the names
  2629. patched in.
  2630.  
  2631. Parameters
  2632. -----------
  2633. url : str
  2634. The discord invite ID or URL (must be a discord.gg URL).
  2635.  
  2636. Raises
  2637. -------
  2638. NotFound
  2639. The invite has expired or is invalid.
  2640. HTTPException
  2641. Getting the invite failed.
  2642.  
  2643. Returns
  2644. --------
  2645. :class:`Invite`
  2646. The invite from the URL/ID.
  2647. """
  2648.  
  2649. invite_id = self._resolve_invite(url)
  2650. data = yield from self.http.get_invite(invite_id)
  2651. self._fill_invite_data(data)
  2652. return Invite(**data)
  2653.  
  2654. @asyncio.coroutine
  2655. def invites_from(self, server):
  2656. """|coro|
  2657.  
  2658. Returns a list of all active instant invites from a :class:`Server`.
  2659.  
  2660. You must have proper permissions to get this information.
  2661.  
  2662. Parameters
  2663. ----------
  2664. server : :class:`Server`
  2665. The server to get invites from.
  2666.  
  2667. Raises
  2668. -------
  2669. Forbidden
  2670. You do not have proper permissions to get the information.
  2671. HTTPException
  2672. An error occurred while fetching the information.
  2673.  
  2674. Returns
  2675. -------
  2676. list of :class:`Invite`
  2677. The list of invites that are currently active.
  2678. """
  2679.  
  2680. data = yield from self.http.invites_from(server.id)
  2681. result = []
  2682. for invite in data:
  2683. channel = server.get_channel(invite['channel']['id'])
  2684. invite['channel'] = channel
  2685. invite['server'] = server
  2686. result.append(Invite(**invite))
  2687.  
  2688. return result
  2689.  
  2690. @asyncio.coroutine
  2691. def accept_invite(self, invite):
  2692. """|coro|
  2693.  
  2694. Accepts an :class:`Invite`, URL or ID to an invite.
  2695.  
  2696. The URL must be a discord.gg URL. e.g. "http://discord.gg/codehere".
  2697. An ID for the invite is just the "codehere" portion of the invite URL.
  2698.  
  2699. Parameters
  2700. -----------
  2701. invite
  2702. The :class:`Invite` or URL to an invite to accept.
  2703.  
  2704. Raises
  2705. -------
  2706. HTTPException
  2707. Accepting the invite failed.
  2708. NotFound
  2709. The invite is invalid or expired.
  2710. Forbidden
  2711. You are a bot user and cannot use this endpoint.
  2712. """
  2713.  
  2714. invite_id = self._resolve_invite(invite)
  2715. yield from self.http.accept_invite(invite_id)
  2716.  
  2717. @asyncio.coroutine
  2718. def delete_invite(self, invite):
  2719. """|coro|
  2720.  
  2721. Revokes an :class:`Invite`, URL, or ID to an invite.
  2722.  
  2723. The ``invite`` parameter follows the same rules as
  2724. :meth:`accept_invite`.
  2725.  
  2726. Parameters
  2727. ----------
  2728. invite
  2729. The invite to revoke.
  2730.  
  2731. Raises
  2732. -------
  2733. Forbidden
  2734. You do not have permissions to revoke invites.
  2735. NotFound
  2736. The invite is invalid or expired.
  2737. HTTPException
  2738. Revoking the invite failed.
  2739. """
  2740.  
  2741. invite_id = self._resolve_invite(invite)
  2742. yield from self.http.delete_invite(invite_id)
  2743.  
  2744. # Role management
  2745.  
  2746. @asyncio.coroutine
  2747. def move_role(self, server, role, position):
  2748. """|coro|
  2749.  
  2750. Moves the specified :class:`Role` to the given position in the :class:`Server`.
  2751.  
  2752. The :class:`Role` object is not directly modified afterwards until the
  2753. corresponding WebSocket event is received.
  2754.  
  2755. Parameters
  2756. -----------
  2757. server : :class:`Server`
  2758. The server the role belongs to.
  2759. role : :class:`Role`
  2760. The role to edit.
  2761. position : int
  2762. The position to insert the role to.
  2763.  
  2764. Raises
  2765. -------
  2766. InvalidArgument
  2767. If position is 0, or role is server.default_role
  2768. Forbidden
  2769. You do not have permissions to change role order.
  2770. HTTPException
  2771. If moving the role failed, or you are of too low rank to move the role.
  2772. """
  2773.  
  2774. if position == 0:
  2775. raise InvalidArgument("Cannot move role to position 0")
  2776.  
  2777. if role == server.default_role:
  2778. raise InvalidArgument("Cannot move default role")
  2779.  
  2780. if role.position == position:
  2781. return # Save discord the extra request.
  2782.  
  2783. url = '{0}/{1.id}/roles'.format(self.http.GUILDS, server)
  2784.  
  2785. change_range = range(min(role.position, position), max(role.position, position) + 1)
  2786.  
  2787. roles = [r.id for r in sorted(filter(lambda x: (x.position in change_range) and x != role, server.roles), key=lambda x: x.position)]
  2788.  
  2789. if role.position > position:
  2790. roles.insert(0, role.id)
  2791. else:
  2792. roles.append(role.id)
  2793.  
  2794. payload = [{"id": z[0], "position": z[1]} for z in zip(roles, change_range)]
  2795. yield from self.http.patch(url, json=payload, bucket='move_role')
  2796.  
  2797. @asyncio.coroutine
  2798. def edit_role(self, server, role, **fields):
  2799. """|coro|
  2800.  
  2801. Edits the specified :class:`Role` for the entire :class:`Server`.
  2802.  
  2803. The :class:`Role` object is not directly modified afterwards until the
  2804. corresponding WebSocket event is received.
  2805.  
  2806. All fields except ``server`` and ``role`` are optional. To change
  2807. the position of a role, use :func:`move_role` instead.
  2808.  
  2809. .. versionchanged:: 0.8.0
  2810. Editing now uses keyword arguments instead of editing the :class:`Role` object directly.
  2811.  
  2812. Parameters
  2813. -----------
  2814. server : :class:`Server`
  2815. The server the role belongs to.
  2816. role : :class:`Role`
  2817. The role to edit.
  2818. name : str
  2819. The new role name to change to.
  2820. permissions : :class:`Permissions`
  2821. The new permissions to change to.
  2822. colour : :class:`Colour`
  2823. The new colour to change to. (aliased to color as well)
  2824. hoist : bool
  2825. Indicates if the role should be shown separately in the online list.
  2826. mentionable : bool
  2827. Indicates if the role should be mentionable by others.
  2828.  
  2829. Raises
  2830. -------
  2831. Forbidden
  2832. You do not have permissions to change the role.
  2833. HTTPException
  2834. Editing the role failed.
  2835. """
  2836.  
  2837. colour = fields.get('colour')
  2838. if colour is None:
  2839. colour = fields.get('color', role.colour)
  2840.  
  2841. payload = {
  2842. 'name': fields.get('name', role.name),
  2843. 'permissions': fields.get('permissions', role.permissions).value,
  2844. 'color': colour.value,
  2845. 'hoist': fields.get('hoist', role.hoist),
  2846. 'mentionable': fields.get('mentionable', role.mentionable)
  2847. }
  2848.  
  2849. yield from self.http.edit_role(server.id, role.id, **payload)
  2850.  
  2851. @asyncio.coroutine
  2852. def delete_role(self, server, role):
  2853. """|coro|
  2854.  
  2855. Deletes the specified :class:`Role` for the entire :class:`Server`.
  2856.  
  2857. Parameters
  2858. -----------
  2859. server : :class:`Server`
  2860. The server the role belongs to.
  2861. role : :class:`Role`
  2862. The role to delete.
  2863.  
  2864. Raises
  2865. --------
  2866. Forbidden
  2867. You do not have permissions to delete the role.
  2868. HTTPException
  2869. Deleting the role failed.
  2870. """
  2871.  
  2872. yield from self.http.delete_role(server.id, role.id)
  2873.  
  2874. @asyncio.coroutine
  2875. def _replace_roles(self, member, roles):
  2876. yield from self.http.replace_roles(member.id, member.server.id, roles)
  2877.  
  2878. @asyncio.coroutine
  2879. def add_roles(self, member, *roles):
  2880. """|coro|
  2881.  
  2882. Gives the specified :class:`Member` a number of :class:`Role` s.
  2883.  
  2884. You must have the proper permissions to use this function.
  2885.  
  2886. The :class:`Member` object is not directly modified afterwards until the
  2887. corresponding WebSocket event is received.
  2888.  
  2889. Parameters
  2890. -----------
  2891. member : :class:`Member`
  2892. The member to give roles to.
  2893. \*roles
  2894. An argument list of :class:`Role` s to give the member.
  2895.  
  2896. Raises
  2897. -------
  2898. Forbidden
  2899. You do not have permissions to add roles.
  2900. HTTPException
  2901. Adding roles failed.
  2902. """
  2903.  
  2904. new_roles = utils._unique(role.id for role in itertools.chain(member.roles, roles))
  2905. yield from self._replace_roles(member, new_roles)
  2906.  
  2907. @asyncio.coroutine
  2908. def remove_roles(self, member, *roles):
  2909. """|coro|
  2910.  
  2911. Removes the :class:`Role` s from the :class:`Member`.
  2912.  
  2913. You must have the proper permissions to use this function.
  2914.  
  2915. The :class:`Member` object is not directly modified afterwards until the
  2916. corresponding WebSocket event is received.
  2917.  
  2918. Parameters
  2919. -----------
  2920. member : :class:`Member`
  2921. The member to revoke roles from.
  2922. \*roles
  2923. An argument list of :class:`Role` s to revoke the member.
  2924.  
  2925. Raises
  2926. -------
  2927. Forbidden
  2928. You do not have permissions to revoke roles.
  2929. HTTPException
  2930. Removing roles failed.
  2931. """
  2932. new_roles = [x.id for x in member.roles]
  2933. for role in roles:
  2934. try:
  2935. new_roles.remove(role.id)
  2936. except ValueError:
  2937. pass
  2938.  
  2939. yield from self._replace_roles(member, new_roles)
  2940.  
  2941. @asyncio.coroutine
  2942. def replace_roles(self, member, *roles):
  2943. """|coro|
  2944.  
  2945. Replaces the :class:`Member`'s roles.
  2946.  
  2947. You must have the proper permissions to use this function.
  2948.  
  2949. This function **replaces** all roles that the member has.
  2950. For example if the member has roles ``[a, b, c]`` and the
  2951. call is ``client.replace_roles(member, d, e, c)`` then
  2952. the member has the roles ``[d, e, c]``.
  2953.  
  2954. The :class:`Member` object is not directly modified afterwards until the
  2955. corresponding WebSocket event is received.
  2956.  
  2957. Parameters
  2958. -----------
  2959. member : :class:`Member`
  2960. The member to replace roles from.
  2961. \*roles
  2962. An argument list of :class:`Role` s to replace the roles with.
  2963.  
  2964. Raises
  2965. -------
  2966. Forbidden
  2967. You do not have permissions to revoke roles.
  2968. HTTPException
  2969. Removing roles failed.
  2970. """
  2971.  
  2972. new_roles = utils._unique(role.id for role in roles)
  2973. yield from self._replace_roles(member, new_roles)
  2974.  
  2975. @asyncio.coroutine
  2976. def create_role(self, server, **fields):
  2977. """|coro|
  2978.  
  2979. Creates a :class:`Role`.
  2980.  
  2981. This function is similar to :class:`edit_role` in both
  2982. the fields taken and exceptions thrown.
  2983.  
  2984. Returns
  2985. --------
  2986. :class:`Role`
  2987. The newly created role. This not the same role that
  2988. is stored in cache.
  2989. """
  2990.  
  2991. data = yield from self.http.create_role(server.id)
  2992. role = Role(server=server, **data)
  2993.  
  2994. # we have to call edit because you can't pass a payload to the
  2995. # http request currently.
  2996. yield from self.edit_role(server, role, **fields)
  2997. return role
  2998.  
  2999. @asyncio.coroutine
  3000. def edit_channel_permissions(self, channel, target, overwrite=None):
  3001. """|coro|
  3002.  
  3003. Sets the channel specific permission overwrites for a target in the
  3004. specified :class:`Channel`.
  3005.  
  3006. The ``target`` parameter should either be a :class:`Member` or a
  3007. :class:`Role` that belongs to the channel's server.
  3008.  
  3009. You must have the proper permissions to do this.
  3010.  
  3011. Examples
  3012. ----------
  3013.  
  3014. Setting allow and deny: ::
  3015.  
  3016. overwrite = discord.PermissionOverwrite()
  3017. overwrite.read_messages = True
  3018. overwrite.ban_members = False
  3019. yield from client.edit_channel_permissions(message.channel, message.author, overwrite)
  3020.  
  3021. Parameters
  3022. -----------
  3023. channel : :class:`Channel`
  3024. The channel to give the specific permissions for.
  3025. target
  3026. The :class:`Member` or :class:`Role` to overwrite permissions for.
  3027. overwrite: :class:`PermissionOverwrite`
  3028. The permissions to allow and deny to the target.
  3029.  
  3030. Raises
  3031. -------
  3032. Forbidden
  3033. You do not have permissions to edit channel specific permissions.
  3034. NotFound
  3035. The channel specified was not found.
  3036. HTTPException
  3037. Editing channel specific permissions failed.
  3038. InvalidArgument
  3039. The overwrite parameter was not of type :class:`PermissionOverwrite`
  3040. or the target type was not :class:`Role` or :class:`Member`.
  3041. """
  3042.  
  3043. overwrite = PermissionOverwrite() if overwrite is None else overwrite
  3044.  
  3045.  
  3046. if not isinstance(overwrite, PermissionOverwrite):
  3047. raise InvalidArgument('allow and deny parameters must be PermissionOverwrite')
  3048.  
  3049. allow, deny = overwrite.pair()
  3050.  
  3051. if isinstance(target, Member):
  3052. perm_type = 'member'
  3053. elif isinstance(target, Role):
  3054. perm_type = 'role'
  3055. else:
  3056. raise InvalidArgument('target parameter must be either Member or Role')
  3057.  
  3058. yield from self.http.edit_channel_permissions(channel.id, target.id, allow.value, deny.value, perm_type)
  3059.  
  3060. @asyncio.coroutine
  3061. def delete_channel_permissions(self, channel, target):
  3062. """|coro|
  3063.  
  3064. Removes a channel specific permission overwrites for a target
  3065. in the specified :class:`Channel`.
  3066.  
  3067. The target parameter follows the same rules as :meth:`edit_channel_permissions`.
  3068.  
  3069. You must have the proper permissions to do this.
  3070.  
  3071. Parameters
  3072. ----------
  3073. channel : :class:`Channel`
  3074. The channel to give the specific permissions for.
  3075. target
  3076. The :class:`Member` or :class:`Role` to overwrite permissions for.
  3077.  
  3078. Raises
  3079. ------
  3080. Forbidden
  3081. You do not have permissions to delete channel specific permissions.
  3082. NotFound
  3083. The channel specified was not found.
  3084. HTTPException
  3085. Deleting channel specific permissions failed.
  3086. """
  3087. yield from self.http.delete_channel_permissions(channel.id, target.id)
  3088.  
  3089. # Voice management
  3090.  
  3091. @asyncio.coroutine
  3092. def move_member(self, member, channel):
  3093. """|coro|
  3094.  
  3095. Moves a :class:`Member` to a different voice channel.
  3096.  
  3097. You must have proper permissions to do this.
  3098.  
  3099. Note
  3100. -----
  3101. You cannot pass in a :class:`Object` instead of a :class:`Channel`
  3102. object in this function.
  3103.  
  3104. Parameters
  3105. -----------
  3106. member : :class:`Member`
  3107. The member to move to another voice channel.
  3108. channel : :class:`Channel`
  3109. The voice channel to move the member to.
  3110.  
  3111. Raises
  3112. -------
  3113. InvalidArgument
  3114. The channel provided is not a voice channel.
  3115. HTTPException
  3116. Moving the member failed.
  3117. Forbidden
  3118. You do not have permissions to move the member.
  3119. """
  3120.  
  3121. if getattr(channel, 'type', ChannelType.text) != ChannelType.voice:
  3122. raise InvalidArgument('The channel provided must be a voice channel.')
  3123.  
  3124. yield from self.http.move_member(member.id, member.server.id, channel.id)
  3125.  
  3126. @asyncio.coroutine
  3127. def join_voice_channel(self, channel):
  3128. """|coro|
  3129.  
  3130. Joins a voice channel and creates a :class:`VoiceClient` to
  3131. establish your connection to the voice server.
  3132.  
  3133. After this function is successfully called, :attr:`voice` is
  3134. set to the returned :class:`VoiceClient`.
  3135.  
  3136. Parameters
  3137. ----------
  3138. channel : :class:`Channel`
  3139. The voice channel to join to.
  3140.  
  3141. Raises
  3142. -------
  3143. InvalidArgument
  3144. The channel was not a voice channel.
  3145. asyncio.TimeoutError
  3146. Could not connect to the voice channel in time.
  3147. ClientException
  3148. You are already connected to a voice channel.
  3149. OpusNotLoaded
  3150. The opus library has not been loaded.
  3151.  
  3152. Returns
  3153. -------
  3154. :class:`VoiceClient`
  3155. A voice client that is fully connected to the voice server.
  3156. """
  3157. if isinstance(channel, Object):
  3158. channel = self.get_channel(channel.id)
  3159.  
  3160. if getattr(channel, 'type', ChannelType.text) != ChannelType.voice:
  3161. raise InvalidArgument('Channel passed must be a voice channel')
  3162.  
  3163. server = channel.server
  3164.  
  3165. if self.is_voice_connected(server):
  3166. raise ClientException('Already connected to a voice channel in this server')
  3167.  
  3168. log.info('attempting to join voice channel {0.name}'.format(channel))
  3169.  
  3170. def session_id_found(data):
  3171. user_id = data.get('user_id')
  3172. guild_id = data.get('guild_id')
  3173. return user_id == self.user.id and guild_id == server.id
  3174.  
  3175. # register the futures for waiting
  3176. session_id_future = self.ws.wait_for('VOICE_STATE_UPDATE', session_id_found)
  3177. voice_data_future = self.ws.wait_for('VOICE_SERVER_UPDATE', lambda d: d.get('guild_id') == server.id)
  3178.  
  3179. # request joining
  3180. yield from self.ws.voice_state(server.id, channel.id)
  3181. session_id_data = yield from asyncio.wait_for(session_id_future, timeout=10.0, loop=self.loop)
  3182. data = yield from asyncio.wait_for(voice_data_future, timeout=10.0, loop=self.loop)
  3183.  
  3184. kwargs = {
  3185. 'user': self.user,
  3186. 'channel': channel,
  3187. 'data': data,
  3188. 'loop': self.loop,
  3189. 'session_id': session_id_data.get('session_id'),
  3190. 'main_ws': self.ws
  3191. }
  3192.  
  3193. voice = VoiceClient(**kwargs)
  3194. try:
  3195. yield from voice.connect()
  3196. except asyncio.TimeoutError as e:
  3197. try:
  3198. yield from voice.disconnect()
  3199. except:
  3200. # we don't care if disconnect failed because connection failed
  3201. pass
  3202. raise e # re-raise
  3203.  
  3204. self.connection._add_voice_client(server.id, voice)
  3205. return voice
  3206.  
  3207. def is_voice_connected(self, server):
  3208. """Indicates if we are currently connected to a voice channel in the
  3209. specified server.
  3210.  
  3211. Parameters
  3212. -----------
  3213. server : :class:`Server`
  3214. The server to query if we're connected to it.
  3215. """
  3216. voice = self.voice_client_in(server)
  3217. return voice is not None
  3218.  
  3219. def voice_client_in(self, server):
  3220. """Returns the voice client associated with a server.
  3221.  
  3222. If no voice client is found then ``None`` is returned.
  3223.  
  3224. Parameters
  3225. -----------
  3226. server : :class:`Server`
  3227. The server to query if we have a voice client for.
  3228.  
  3229. Returns
  3230. --------
  3231. :class:`VoiceClient`
  3232. The voice client associated with the server.
  3233. """
  3234. return self.connection._get_voice_client(server.id)
  3235.  
  3236. def group_call_in(self, channel):
  3237. """Returns the :class:`GroupCall` associated with a private channel.
  3238.  
  3239. If no group call is found then ``None`` is returned.
  3240.  
  3241. Parameters
  3242. -----------
  3243. channel: :class:`PrivateChannel`
  3244. The group private channel to query the group call for.
  3245.  
  3246. Returns
  3247. --------
  3248. Optional[:class:`GroupCall`]
  3249. The group call.
  3250. """
  3251. return self.connection._calls.get(channel.id)
  3252.  
  3253. # Miscellaneous stuff
  3254.  
  3255. @asyncio.coroutine
  3256. def application_info(self):
  3257. """|coro|
  3258.  
  3259. Retrieve's the bot's application information.
  3260.  
  3261. Returns
  3262. --------
  3263. :class:`AppInfo`
  3264. A namedtuple representing the application info.
  3265.  
  3266. Raises
  3267. -------
  3268. HTTPException
  3269. Retrieving the information failed somehow.
  3270. """
  3271. data = yield from self.http.application_info()
  3272. return AppInfo(id=data['id'], name=data['name'],
  3273. description=data['description'], icon=data['icon'],
  3274. owner=User(**data['owner']))
  3275.  
  3276. @asyncio.coroutine
  3277. def get_user_info(self, user_id):
  3278. """|coro|
  3279.  
  3280. Retrieves a :class:`User` based on their ID. This can only
  3281. be used by bot accounts. You do not have to share any servers
  3282. with the user to get this information, however many operations
  3283. do require that you do.
  3284.  
  3285. Parameters
  3286. -----------
  3287. user_id: str
  3288. The user's ID to fetch from.
  3289.  
  3290. Returns
  3291. --------
  3292. :class:`User`
  3293. The user you requested.
  3294.  
  3295. Raises
  3296. -------
  3297. NotFound
  3298. A user with this ID does not exist.
  3299. HTTPException
  3300. Fetching the user failed.
  3301. """
  3302. data = yield from self.http.get_user_info(user_id)
  3303. return User(**data)
Add Comment
Please, Sign In to add comment