Exemple #1
0
    async def aquran(self, *, ref: str):

        try:
            quranSpec = self.getSpec(ref)
        except:
            await self.bot.say(
                "Invalid arguments! Do `{0}aquran [surah]:[ayah]`. "
                "Example: `{0}aquran 1:1`"
                "\n"
                "To quote multiple verses, do `{0}quran [surah]:[first ayah]-[last ayah]`"
                "\n"
                "Example: `{0}aquran 1:1-7`.".format(prefix))
            return

        try:
            surah_name = await self.getMetadata(quranSpec)
            await self.getVerses(quranSpec)

            em = makeEmbed(fields=quranSpec.orderedDict,
                           author=surah_name,
                           author_icon=icon,
                           colour=0x78c741,
                           inline=False)
            await self.bot.say(embed=em)

        except:
            print(Exception)
Exemple #2
0
    async def aquran(self, ctx, *, ref: str):

        try:
            quranSpec = self.getSpec(ref)
        except:
            await ctx.send(INVALID_ARGUMENTS_ARABIC.format(prefix))
            return

        surah_name = await self.getMetadata(quranSpec, edition='ar')
        await self.getVerses(quranSpec, quranCom=False)

        em = makeEmbed(fields=quranSpec.orderedDict,
                       author=surah_name,
                       author_icon=icon,
                       colour=0x78c741,
                       inline=False)
        await ctx.send(embed=em)
Exemple #3
0
    async def search(self, ctx, *, arg):

        api_key = open("google-api-key.txt", "r").read()
        cse_id = open("cse-id.txt", "r").read()

        def search(arg, api_key, cse_id, **kwargs):

            service = build("customsearch", "v1", developerKey=api_key)
            res = service.cse().list(q=arg, cx=cse_id, **kwargs).execute()
            return res['items']

        results = search(arg, api_key, cse_id, num=7)
        o = OrderedDict()

        for result in results:
            title = result['title']
            o['{}'.format(title)] = result['link']

        em = makeEmbed(fields=o, author=f'Results for {arg.title()}', author_icon=icon, colour=0x78c741, inline= False)
        await ctx.send(embed=em)
Exemple #4
0
    async def tafsir(self, ctx, ref: str, tafsir: str = None):

        # Debug info
        sender = ctx.message.author
        server = ctx.message.server
        serverid = ctx.message.server.id

        print(f'{sender} executed command tafsir on {server} ({serverid})')

        if tafsir is None:
            tafsir = 'ar.jalalayn'
            await self.bot.say('Defaulting to Tafsir al-Jalalayn.')
        elif tafsir in tafsir_list:
            tafsir = 'ar.' + tafsir
        else:
            await self.bot.say(f'Invalid tafsir. Valid tafsirs are: `{tafsir_list}`')
            return

        try:
            tafsirSpec = self.getSpec(ref, tafsir = tafsir)
        except:
            await self.bot.say("Invalid arguments! Do `{0}tafsir [surah]:[ayah] (optional tafsir name)`. "
                               "Example: `{0}tafsir 1:1`"
                               "\n\n"
                               "To quote multiple verses, do `{0}tafsir [surah]:[first ayah]-[last ayah]`"
                               "\n\n"
                               "Example 2: `{0}tafsir 1:1-7 muyassar`"
                               "\n\n"
                               "**Valid editions**: `{1}`".format(prefix, tafsir_list))
            return

        await self.getTafsirs(tafsirSpec)
        readableTafsirName = self.getReadableTafsirName(tafsir)

        em = makeEmbed(fields=tafsirSpec.orderedDict, author=readableTafsirName, author_icon=icon, colour=0x467f05,
                       inline=False)

        await self.bot.say(embed=em)
Exemple #5
0
    async def quran(self, ref: str, edition: str = 'en.sahih'):

        if edition in edition_list:
            edition = 'en.' + edition
        elif edition != 'en.sahih':
            await self.bot.say(
                f'Invalid translation. Valid translation editions are: `{edition_list}`'
            )

        try:
            quranSpec = self.getSpec(ref, edition=edition)
        except:
            await self.bot.say(
                "Invalid arguments! Do `{0}quran [surah]:[ayah] (edition)`. "
                "Example: `{0}quran 1:1`"
                "\n"
                "Example 2: `{0}quran 1:1 yusufali`"
                "\n\n"
                "To quote multiple verses, do `{0}quran [surah]:[first ayah]-[last ayah]`"
                "\n"
                "Example: `{0}quran 1:1-7`.".format(prefix))
            return

        try:

            surah_name, readableEdition = await self.getMetadata(quranSpec)
            await self.getVerses(quranSpec)

            em = makeEmbed(fields=quranSpec.orderedDict,
                           author=f'Surah {surah_name} - {readableEdition}',
                           author_icon=icon,
                           colour=0x78c741,
                           inline=False)
            await self.bot.say(embed=em)

        except:
            print(Exception)
Exemple #6
0
    async def quran(self, ctx, ref: str, edition: str = None):

        db = mysql.connector.connect(host=self.host,
                                     user=self.user,
                                     passwd=self.password,
                                     database=self.database)
        server = ctx.message.guild.id
        cursor = db.cursor(buffered=True)
        sql = "INSERT IGNORE INTO bot (server, translation) VALUES (%s, %s)"
        val = (f"{server}", "sahih")
        cursor.execute(sql, val)
        db.commit()

        if edition is None:
            cursor.execute(
                f"SELECT translation FROM bot WHERE server = {server}")
            edition = str(cursor.fetchone()[0])
            print(edition)
        cursor.close()
        edition = edition.lower()

        if edition in self.quranComEditions:
            quranCom = True

        else:
            quranCom = False

        try:
            edition = self.formatEdition(edition)

            try:
                quranSpec = self.getSpec(ref, edition=edition)

            except:

                await ctx.send(
                    "Invalid arguments! Do `{0}quran [surah]:[ayah] [edition]`. "
                    "Example: `{0}quran 1:1`"
                    "\n"
                    "Example 2: `{0}quran 1:1 yusufali`"
                    "\n\n"
                    "To quote multiple verses, do `{0}quran [surah]:[first ayah]-[last ayah]`"
                    "\n"
                    "Example: `{0}quran 1:1-7`.".format(prefix))
                return

            try:

                surah_name, readableEdition, englishSurahName, revelationType = await self.getMetadata(
                    quranSpec, edition)

                await self.getVerses(quranSpec, quranCom)

                em = makeEmbed(
                    fields=quranSpec.orderedDict,
                    author=f"Surah {surah_name} ({englishSurahName})",
                    author_icon=icon,
                    colour=0x78c741,
                    inline=False)
                em.set_footer(
                    text=f'Translation: {readableEdition} | {revelationType}')
                await ctx.send(embed=em)

            except Exception as e:

                print(e)

        except:
            await ctx.send(
                f'Invalid translation. A list can be found at:\n'
                '<https://github.com/galacticwarrior9/islambot/blob/master/Translations.md>'
            )
	async def mhandle(self, message: Message):
		"""
		Handles $(prefix)module commands
		:param message: the message with the command
		"""
		# remove "module" from the command
		txt = message.content
		if txt.startswith('modules'):
			txt = txt[7::]
		elif txt.startswith('module'):
			txt = txt[6::]
		# split only the first line
		cmd = txt.split('\n')[0].split()

		if cmd[0] == '':
			del cmd[0]

		if len( cmd ) == 0:
			await message.channel.send(
				f'missing subcommand, subcommands available: add, update, remove, list'
			)
			return

		action, name = 'error', 'None'
		match cmd:
			case [ 'remove' ]:
				# remove without argument
				await message.channel.send(
					f'missing parameter <modulename>.'
					f'you can list all modules using {bot.Bot.getInstance().prefix}modules list all'
				)
				action = 'remove'
			case [ 'remove', name ]:
				# remove with argument
				# module check
				if cmd[ 1 ] not in self.modules:
					await message.channel.send(
						f'the specified module ({cmd[ 1 ]}) does not exist.'
						f'you can list all modules using {bot.Bot.getInstance().prefix}modules list all'
					)
					return
				# author check
				if message.author.id not in (self.modules[ cmd[ 1 ] ].author, utils.enderzombi):
					await message.channel.send(
						f'only {await message.guild.fetch_member( self.modules[ cmd[ 1 ] ].author )} can delete this module'
					)
					return
				os.remove( self.modules[ cmd[ 1 ] ].path )
				del self.modules[ cmd[ 1 ] ]
				await message.channel.send( f'removed module "{cmd[ 1 ]}"' )
				action = 'remove'

			case [ 'list' ] | [ 'list', 'all' ]:
				modules = [ ]
				for name, module in self.modules.items():
					modules.append(
						f'{name}{"" if module.isInitialized else "*"} by {await message.channel.guild.fetch_member( module.author )}'
					)
				if len( modules ) == 0:
					modules.append( 'no modules found' )
				await message.channel.send(
					embed=utils.makeEmbed(
						title='Module list',
						content='\n'.join( modules ),
						color=discord.Color.blue(),
						footer='modules with a leading * are disabled\nICGbot by (mainly) ENDERZOMBI102'
					)
				)
				action = 'list'
			case [ 'list', author ]:
				modules = []
				if ( len( message.mentions ) == 0 ) or ( len( message.mentions ) > 1 ):
					await message.channel.send( f'should have as parameter exactly ONE mention or "all"' )
				else:
					user = utils.getUserIdFromText( author )
					for name, module in self.modules.items():
						if module.author == user:
							modules.append( f'{name}{"" if module.isInitialized else "*"}' )
					if len( modules ) == 0:
						modules.append( "seems like this user didn't made any module" )
					await message.channel.send(
						embed=utils.makeEmbed(
							title=f'Modules Made By {author}',
							content='\n'.join( modules ),
							color=discord.Color.blue(),
							footer='modules with a leading * are disabled\nICGbot by (mainly) ENDERZOMBI102'
						)
					)
					action = 'list'

			case [ 'add', name ]:
					# exist check
					if name in self.modules:
						await message.channel.send(f'module "{name}" already exist! use module update to update it' )
						return

					path = await saveCode( message, name )
					try:
						self.modules[ name ] = Module( message.author.id, Path( path ) )
					except AttributeError:
						await message.channel.send( 'missing module (.py) file' )
					except Exception as e:
						await utils.send( message, embed=utils.getTracebackEmbed( e ) )
						return
					action = 'added'

			case [ 'update' | 'edit' ]:
				await message.channel.send( f'missing parameter <modulename>.' )
				return

			case [ 'update' | 'edit', name ]:
					# exist check
					if name not in self.modules:
						await message.channel.send(f'module "{name}" does not exist! use module add to add it' )
						return
					# author check
					if self.modules[ name ].author != message.author.id:
						await message.channel.send( f"You're not the author of {name}!" )
						return

					await saveCode( message, name )
					action = 'updated'

			case [ comm ]:
				await message.channel.send( f'error, no subcommand named {comm}' )

		# notify for command completition
		await message.channel.send( f'module "{name}" successfully {action}' )

		# save everything
		with open('./options', 'r') as file:
			data = bjson.load( file )
		# update with new data
		data['modules'] = {}
		for module in self.modules.values():
			data[ 'modules' ].update( module.asDict() )
		# write options
		with open('./options', 'w') as file:
			bjson.dump( data, file )
Exemple #8
0
    async def quran(self, ctx, ref: str, edition: str = None):
        async with ctx.channel.typing():

            # If no translation is specified, contact the MySQL database to see if the server set a default one.

            if edition is None:

                try:
                    connection = MySQL.connection_pool.get_connection()
                    cursor = connection.cursor(buffered=True)
                    cursor.execute(
                        f"SELECT translation FROM bot WHERE server = {ctx.message.guild.id}"
                    )
                    result = cursor.fetchone()
                    connection.close()

                    # If the server has not set a default translation, use Sahih International.
                    if result is None:
                        edition = "en.sahih"

                    # Use the server default if found:
                    else:
                        edition = self.formatEdition(result[0])

                # If the database cannot be reached, fall back to Sahih International.
                except:
                    edition = "en.sahih"

            # If a translation was specified in the command, check whether it is valid:
            else:
                try:
                    edition = self.formatEdition(edition)
                except KeyError:
                    await ctx.send(INVALID_TRANSLATION)
                    return

            # Check if the verses need to be fetched from quran.com.
            if edition in self.quranComEditions:
                quranCom = True

            else:
                quranCom = False

            # Now fetch the verses:
            try:
                quranSpec = self.getSpec(ref, edition=edition)

            except:
                await ctx.send(INVALID_ARGUMENTS_ENGLISH.format(prefix))
                return

            surah_name, readableEdition, englishSurahName, revelationType = await self.getMetadata(
                quranSpec, edition)

            await self.getVerses(quranSpec, quranCom)

            em = makeEmbed(fields=quranSpec.orderedDict,
                           author=f"Surah {surah_name} ({englishSurahName})",
                           author_icon=icon,
                           colour=0x78c741,
                           inline=False)
            em.set_footer(
                text=f'Translation: {readableEdition} | {revelationType}')
            await ctx.send(embed=em)